-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path189_rotate_array.cpp
More file actions
40 lines (33 loc) · 891 Bytes
/
189_rotate_array.cpp
File metadata and controls
40 lines (33 loc) · 891 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
class Solution {
public:
void rotate(vector<int>& nums, int k) {
int len = nums.size();
// if len <= k
// ensure k is always < len
if (len <= k) {
k = k % len;
}
// do nothing if k = 0
if (k == 0) {
return;
}
int a = len, b = k, mcd;
while(b != 0) {
mcd = b;
b = a % b;
a = mcd;
}
// there are an mcd number of cycles
for (int i = 0; i < mcd; ++i){
int start = len - 1 - i;
int temp = nums[start];
// replace items in the cycle until the start is reached
int j = start - k;
while (j != start) {
nums[(j + k) % len] = nums[j];
j = (j - k + len) % len;
}
nums[(j + k) % len] = temp;
}
}
};