-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathleetcode189_rotate_array.cpp
72 lines (58 loc) · 1.39 KB
/
leetcode189_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
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
70
71
72
/**
* @file leetcode189_rotate_array.cpp
* @author wangguibao(https://github.com/wangguibao)
* @date 2023/05/27 14:36
* @brief https://leetcode.com/problems/rotate-array/
*
**/
#include <iostream>
#include <vector>
#include <stack>
using namespace std;
class Solution {
public:
void rotate(vector<int>& nums, int k) {
size_t len = nums.size();
k %= len;
auto b = nums.begin();
auto e = b + (len - k);
std::vector<int> vec1(b, e);
std::vector<int> vec2(e, nums.end());
int i = 0;
for (auto x: vec2) {
nums[i++] = x;
}
for (auto x: vec1) {
nums[i++] = x;
}
}
};
int main() {
int n;
std::vector<int> nums;
while (1) {
n = 0;
std::cout << "Number of elements: ";
std::cin >> n;
if (n <= 0) {
return 0;
}
std::cout << n << " integers: " << std::endl;
nums.clear();
int ele;
for (int i = 0; i < n; ++i) {
std::cin >> ele;
nums.push_back(ele);
}
std::cout << "Rotate: ";
int k;
cin >> k;
Solution solution;
solution.rotate(nums, k);
for (auto e: nums) {
std::cout << e;
}
std::cout << std::endl;
}
return 0;
}