-
Notifications
You must be signed in to change notification settings - Fork 0
/
189-rotate-array.cpp
40 lines (33 loc) · 1.25 KB
/
189-rotate-array.cpp
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
// Title: Rotate Array
// Description:
// Given an array, rotate the array to the right by k steps, where k is non-negative.
// Link: https://leetcode.com/problems/rotate-array/
// Time complexity: O(n)
// Space complexity: O(1)
class Solution {
public:
void rotate(std::vector<int> &nums, int k) {
// normalize k
k %= nums.size();
const std::size_t N = nums.size();
const std::size_t negK = N - k;
const std::size_t cycleGap = std::gcd(k, N);
// early return if there is no need to rotate
if (N == 0 || k == 0) return;
// rotate the elements for each disjoint cycle
for (std::size_t offset = 0; offset != cycleGap; ++offset) {
int tmp = nums[offset];
std::size_t destIndex = offset;
for (std::size_t i = 1; i != N / cycleGap; ++i) {
std::size_t srcIndex = (destIndex + negK) % N;
nums[destIndex] = nums[srcIndex];
destIndex = srcIndex;
}
nums[offset + k] = tmp;
}
}
// void rotate(std::vector<int> &nums, int k) {
// // utilize the standard library to solve the problem
// std::rotate(nums.begin(), nums.end() - k % nums.size(), nums.end());
// }
};