-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path189.cpp
More file actions
70 lines (58 loc) · 1.41 KB
/
189.cpp
File metadata and controls
70 lines (58 loc) · 1.41 KB
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
/*
* Written by Nitin Kumar Maharana
* nitin.maharana@gmail.com
*/
class Solution {
int len;
public:
void rotate(vector<int>& nums, int k) {
len = nums.size();
if(!len)
return;
int number, temp, currIndex, nextIndex;
int count, origin;
currIndex = 0;
number = nums[currIndex];
count = len;
origin = 0;
while(count--)
{
nextIndex = ((currIndex+k) % len);
temp = nums[nextIndex];
nums[nextIndex] = number;
number = temp;
currIndex = nextIndex;
if(currIndex == origin)
{
origin += 1;
currIndex = origin;
number = nums[currIndex];
}
}
}
};
//One more solution using reverse.
class Solution {
int len;
void reverseArray(vector<int>& nums, int l, int r)
{
int t;
while(l < r)
{
t = nums[l];
nums[l++] = nums[r];
nums[r--] = t;
}
return;
}
public:
void rotate(vector<int>& nums, int k) {
len = nums.size();
if(!len)
return;
k = k % len;
reverseArray(nums, len-k, len-1);
reverseArray(nums, 0, len-k-1);
reverseArray(nums, 0, len-1);
}
};