Fork me on GitHub

Rotate Array

Description

https://leetcode.com/problems/rotate-array/description/

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public:
void rotate(vector<int>& nums, int k) {
int count = 0;
int start = 0;
int pre = nums[0];
int index = start;
while(count < nums.size()) {
count += 1;
int nextIndex = (index + k) % nums.size();
int temp = nums[nextIndex];
nums[nextIndex] = pre;
pre = temp;
index = nextIndex;
if (index == start) {start += 1; index += 1; pre = nums[index];}
cout << index << endl;
}
}
};