diff options
author | 3gg <3gg@shellblade.net> | 2025-02-05 18:36:31 -0800 |
---|---|---|
committer | 3gg <3gg@shellblade.net> | 2025-02-05 18:36:31 -0800 |
commit | 4689e4e80b479be25f7557d05818f5caa723aafa (patch) | |
tree | 4df25811fe2a9a15b401375178da6537f4b6063f /top-interview-questions/easy/array/03_rotate_array.cc |
Diffstat (limited to 'top-interview-questions/easy/array/03_rotate_array.cc')
-rw-r--r-- | top-interview-questions/easy/array/03_rotate_array.cc | 39 |
1 files changed, 39 insertions, 0 deletions
diff --git a/top-interview-questions/easy/array/03_rotate_array.cc b/top-interview-questions/easy/array/03_rotate_array.cc new file mode 100644 index 0000000..19f66dd --- /dev/null +++ b/top-interview-questions/easy/array/03_rotate_array.cc | |||
@@ -0,0 +1,39 @@ | |||
1 | class Solution { | ||
2 | public: | ||
3 | // Works, but it's slow. | ||
4 | /*int gcd(int a, int b) { | ||
5 | if (a == 0) return b; | ||
6 | if (b == 0) return a; | ||
7 | if (a == b) return a; | ||
8 | if (a > b) return gcd(a-b, b); | ||
9 | else return gcd(a, b-a); | ||
10 | }*/ | ||
11 | |||
12 | // Much faster than the above implementation. | ||
13 | int gcd(int a, int b) { | ||
14 | if (b == 0) return a; | ||
15 | else return gcd(b, a%b); | ||
16 | } | ||
17 | |||
18 | void rotate(vector<int>& nums, int k) { | ||
19 | const size_t N = nums.size(); | ||
20 | if ((N <= 1) || (k == 0)) { | ||
21 | return; | ||
22 | } | ||
23 | // Original algorithm only works for (N,k) coprime. | ||
24 | // Break the cycles when we complete a loop around the array. | ||
25 | const int gcdNk = gcd(N,k); | ||
26 | const int steps = (gcdNk != 1) ? (N / gcdNk) : N; | ||
27 | int start = -1; | ||
28 | for (size_t n = 0; n < N; n += steps) { | ||
29 | ++start; | ||
30 | int i = start; | ||
31 | int i_val = nums[i]; | ||
32 | for (size_t s = 0; s < steps; ++s) { | ||
33 | const int next = (i+k) % N; | ||
34 | std::swap(i_val, nums[next]); | ||
35 | i = next; | ||
36 | } | ||
37 | } | ||
38 | } | ||
39 | }; | ||