diff --git a/189-rotate-array/driver.cpp b/189-rotate-array/driver.cpp new file mode 100644 index 0000000..340677b --- /dev/null +++ b/189-rotate-array/driver.cpp @@ -0,0 +1,11 @@ +#include "soln.hpp" + +int main() +{ + vector nums = {1, 2, 3, 4, 5, 6, 7}; + int k = 9; + vector answer = {6, 7, 1, 2, 3, 4, 5}; + Solution soln; + cout << "Rotated array correctly? " << soln.test(nums, k, answer) << endl; + return 0; +} \ No newline at end of file diff --git a/189-rotate-array/soln.cpp b/189-rotate-array/soln.cpp new file mode 100644 index 0000000..4bb43f6 --- /dev/null +++ b/189-rotate-array/soln.cpp @@ -0,0 +1,20 @@ +#include "soln.hpp" + +void Solution::rotate(vector &nums, int k) +{ + int n = nums.size(); + if (n != 1) + { + k %= n; + vector result(nums.begin() + (nums.size() - k), nums.end()); + result.insert(result.end(), nums.begin(), nums.end() - k); + nums = result; + } +} + +bool Solution::test(vector &nums, int k, vector &answer) +{ + vector nums_copy(nums); + rotate(nums_copy, k); + return nums_copy == answer; +} \ No newline at end of file diff --git a/189-rotate-array/soln.hpp b/189-rotate-array/soln.hpp new file mode 100644 index 0000000..90aa94b --- /dev/null +++ b/189-rotate-array/soln.hpp @@ -0,0 +1,8 @@ +#include +using namespace std; +class Solution +{ +public: + void rotate(vector &nums, int k); + bool test(vector &nums, int k, vector &answer); +}; \ No newline at end of file