forked from timoncui/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRotate_Array.cpp
More file actions
69 lines (59 loc) · 1.51 KB
/
Rotate_Array.cpp
File metadata and controls
69 lines (59 loc) · 1.51 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
/*
Author: Timon Cui, [email protected]
Title: Rotate Array
Description:
Given a list, rotate the list to the right by k places, where k is non-negative.
For example:
Given 1->2->3->4->5->NULL and k = 2,
return 4->5->1->2->3->NULL.
Difficulty rating: Easy
Source:
http://www.leetcode.com/2010/04/rotating-array-in-place.html
http://www.cs.bell-labs.com/cm/cs/pearls/s02b.pdf
http://basicalgos.blogspot.com/2012/04/40-rotate-array-in-place.html
Notes:
*/
#include "utils.hpp"
template <class T>
void rotate1(std::vector<T>& x, const int N) {
std::reverse(x.begin(), x.begin() + N);
std::reverse(x.begin() + N, x.end());
std::reverse(x.begin(), x.end());
}
template <class T>
void rotate2(std::vector<T>& x, int k) {
int beg = 0, end = x.size(), mid = k;
while (beg < mid) {
std::swap(x[beg++], x[mid++]);
if (mid == end) mid = k;
else if (beg == k) k = mid;
}
}
int main( int argc, char* argv[] ) {
const int N = 100;
std::vector<int> a(N), b(N);
std::vector<int> offsets(3);
offsets[0] = 3;
offsets[1] = 94;
offsets[2] = 50;
{
for (int j = 0; j < (int)offsets.size(); ++j) {
for (int i = 0; i < N; ++i) {
a[i] = i;
b[i] = (i + offsets[j]) % N;
}
rotate1(a, offsets[j]);
eq(j, a, b);
}
}
{
for (int j = 0; j < (int)offsets.size(); ++j) {
for (int i = 0; i < N; ++i) {
a[i] = i;
b[i] = (i + offsets[j]) % N;
}
rotate2(a, offsets[j]);
eq(j, a, b);
}
}
}