Skip to content

Commit

Permalink
Rotate array (#210)
Browse files Browse the repository at this point in the history
* add rotate array

* impl rotate array
  • Loading branch information
SKTT1Ryze authored Mar 15, 2024
1 parent 4b122e1 commit f69e5d6
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 0 deletions.
49 changes: 49 additions & 0 deletions leetcode-cc/RotateArray.hpp
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());
}
};
6 changes: 6 additions & 0 deletions runtime-cc/src/registration.cc
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,7 @@
#include "../leetcode-cc/ReverseNodesinKGroup.hpp"
#include "../leetcode-cc/ReverseWords.hpp"
#include "../leetcode-cc/RomanToInteger.hpp"
#include "../leetcode-cc/RotateArray.hpp"
#include "../leetcode-cc/SameTree.hpp"
#include "../leetcode-cc/ScrambleString.hpp"
#include "../leetcode-cc/SearchInRotaedSortedArray.hpp"
Expand Down Expand Up @@ -789,5 +790,10 @@ const int registerAll(std::shared_ptr<Container> handle) {
return std::make_shared<SBestTimeToBuySellStockIV>();
});

handle->registerProblem(
[]() -> ArcProblem { return std::make_shared<PRotateArray>(); });
handle->registerSolution(
[]() -> ArcSolution { return std::make_shared<SRotateArray>(); });

return 0;
}

0 comments on commit f69e5d6

Please sign in to comment.