forked from kaidul/LeetCode_problems_solution
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Rotate_Array.cpp
41 lines (37 loc) · 1013 Bytes
/
Rotate_Array.cpp
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
41
class Solution {
public:
// reversal algorithm; time: O(n)
void swapRange(vector<int>& nums, int left, int right) {
--right;
while(left < right) {
swap(nums[left], nums[right]);
left++, right--;
}
}
void rotate(vector<int>& nums, int k) {
int n = nums.size();
k %= n;
swapRange(nums, 0, n - k);
swapRange(nums, n - k, n);
swapRange(nums, 0, n);
}
};
// shifting
class Solution {
public:
void rotate(vector<int>& nums, int k) {
int n = (int) nums.size();
k %= n;
int count = 0;
for(int start = 0; count < n; start++) {
int currIndx = start;
int tmp = nums[currIndx];
do {
int nextIndx = (currIndx + k) % n;
swap(tmp, nums[nextIndx]);
currIndx = nextIndx;
count++;
} while(currIndx != start);
}
}
};