Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Rotate array #210

Merged
merged 2 commits into from
Mar 15, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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;
}
Loading