forked from MaskRay/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
rotate-array.cc
44 lines (40 loc) · 758 Bytes
/
rotate-array.cc
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
// Rotate Array
class Solution {
public:
void rotate(vector<int> &a, int k) {
int n = a.size();
k = (n-k%n)%n;
reverse(a.begin(), a.begin()+k);
reverse(a.begin()+k, a.end());
reverse(a.begin(), a.end());
}
};
/// 拆成若干置換
#define FOR(i, a, b) for (int i = (a); i < (b); i++)
#define REP(i, n) FOR(i, 0, n)
int gcd(int a, int b)
{
int t;
while (b)
t = a%b, a = b, b = t;
return a;
}
class Solution {
public:
void rotate(vector<int> &a, int m) {
int n = a.size();
m %= n;
int d = gcd(n, m);
REP(i, d) {
int j = i, x = a[j];
for(;;) {
int k = j-m;
if (k < 0) k += n;
if (k == i) break;
a[j] = a[k];
j = k;
}
a[j] = x;
}
}
};