day 17: 189-rotate-array

This commit is contained in:
Kaushik Narayan R 2023-10-16 21:58:22 -07:00
parent b634dfae36
commit 37153b50f1
3 changed files with 39 additions and 0 deletions

View 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
View 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;
}

View 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);
};