-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQ2.cpp
More file actions
42 lines (33 loc) · 864 Bytes
/
Q2.cpp
File metadata and controls
42 lines (33 loc) · 864 Bytes
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
#include <iostream>
#include <vector>
void rotate(std::vector<int>& nums, int k) {
int n = nums.size();
k = k % n;
int count = 0;
for (int start = 0; count < n; ++start) {
int current = start;
int prev = nums[start];
do {
int next = (current + k) % n;
std::swap(nums[next], prev);
current = next;
++count;
} while (start != current);
}
}
int main() {
std::vector<int> nums = {11, 24, 20, 32, 64};
int k = 2;
std::cout << "Original array: ";
for (int num : nums) {
std::cout << num << " ";
}
std::cout << std::endl;
rotate(nums, k);
std::cout << "array after rotating by " << k << " steps to the right: ";
for (int num : nums) {
std::cout << num << " ";
}
std::cout << std::endl;
return 0;
}