mirror of
https://github.com/20kaushik02/leetcode-gulag.git
synced 2025-12-06 07:34:06 +00:00
day 17: 189-rotate-array
This commit is contained in:
parent
b634dfae36
commit
37153b50f1
11
189-rotate-array/driver.cpp
Normal file
11
189-rotate-array/driver.cpp
Normal file
@ -0,0 +1,11 @@
|
||||
#include "soln.hpp"
|
||||
|
||||
int main()
|
||||
{
|
||||
vector<int> nums = {1, 2, 3, 4, 5, 6, 7};
|
||||
int k = 9;
|
||||
vector<int> answer = {6, 7, 1, 2, 3, 4, 5};
|
||||
Solution soln;
|
||||
cout << "Rotated array correctly? " << soln.test(nums, k, answer) << endl;
|
||||
return 0;
|
||||
}
|
||||
20
189-rotate-array/soln.cpp
Normal file
20
189-rotate-array/soln.cpp
Normal file
@ -0,0 +1,20 @@
|
||||
#include "soln.hpp"
|
||||
|
||||
void Solution::rotate(vector<int> &nums, int k)
|
||||
{
|
||||
int n = nums.size();
|
||||
if (n != 1)
|
||||
{
|
||||
k %= n;
|
||||
vector<int> result(nums.begin() + (nums.size() - k), nums.end());
|
||||
result.insert(result.end(), nums.begin(), nums.end() - k);
|
||||
nums = result;
|
||||
}
|
||||
}
|
||||
|
||||
bool Solution::test(vector<int> &nums, int k, vector<int> &answer)
|
||||
{
|
||||
vector<int> nums_copy(nums);
|
||||
rotate(nums_copy, k);
|
||||
return nums_copy == answer;
|
||||
}
|
||||
8
189-rotate-array/soln.hpp
Normal file
8
189-rotate-array/soln.hpp
Normal file
@ -0,0 +1,8 @@
|
||||
#include <bits/stdc++.h>
|
||||
using namespace std;
|
||||
class Solution
|
||||
{
|
||||
public:
|
||||
void rotate(vector<int> &nums, int k);
|
||||
bool test(vector<int> &nums, int k, vector<int> &answer);
|
||||
};
|
||||
Loading…
x
Reference in New Issue
Block a user