-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path189. Rotate Array
43 lines (36 loc) · 904 Bytes
/
189. Rotate Array
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
42
43
class Solution {
public:
void rotate(vector<int>& nums, int k)
{
int n = nums.size();
int i , j ;
while(k>n)
{
k = k - n;
}
i = 0, j = nums.size()-k-1;
//reverse the left of the array
while(i<j)
{
swap(nums[i],nums[j]);
i++;
j--;
}
i = nums.size()-k, j = nums.size()-1;
//reverse the k elements of the array
while(i<j)
{
swap(nums[i], nums[j]);
i++;
j--;
}
i = 0, j = nums.size()-1;
//reverse total elements of the array
while(i<j)
{
swap(nums[i], nums[j]);
i++;
j--;
}
}
};