-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
* add rotate array * impl rotate array
- Loading branch information
Showing
2 changed files
with
55 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,49 @@ | ||
#include <deque> | ||
|
||
#include "TestHelper.h" | ||
#include "problem.h" | ||
#include "solution.h" | ||
|
||
using namespace std; | ||
|
||
IMPLEMENT_PROBLEM_CLASS(PRotateArray, 189, DIFFI_MEDIUM, TOPIC_ALGORITHMS, | ||
"Rotate Array", | ||
"Given an integer array nums, rotate the array to the " | ||
"right by k steps, where k is non-negative.", | ||
{"Array"}); | ||
|
||
class SRotateArray : public ISolution { | ||
public: | ||
size_t problemId() const override { return 189; } | ||
string name() const override { | ||
return ("Solution for " + string("Rotate Array")); | ||
} | ||
string location() const override { return __FILE_NAME__; } | ||
int test() const override { | ||
vector<int> nums = {1, 2, 3, 4, 5, 6, 7}; | ||
int k = 3; | ||
this->rotate(nums, k); | ||
if (nums == vector({5, 6, 7, 1, 2, 3, 4})) { | ||
return 0; | ||
} else { | ||
return 1; | ||
} | ||
}; | ||
int benchmark() const override { return 0; } | ||
|
||
private: | ||
void rotate(vector<int>& nums, int k) const { | ||
int n = nums.size(); | ||
k = k % n; | ||
deque<int> v = {}; | ||
|
||
while (k) { | ||
int e = nums.back(); | ||
nums.pop_back(); | ||
v.push_front(e); | ||
k--; | ||
} | ||
|
||
nums.insert(nums.begin(), v.begin(), v.end()); | ||
} | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters