-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path089_Rotate_Array
More file actions
51 lines (41 loc) · 1.04 KB
/
Copy path089_Rotate_Array
File metadata and controls
51 lines (41 loc) · 1.04 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
Given an integer array nums, rotate the array to the right by k steps, where k is non-negative.
Input: nums = [1,2,3,4,5,6,7], k = 3
Output: [5,6,7,1,2,3,4]
BruteForce (TLE)
class Solution {
public:
void rotate(vector<int>& nums, int k) {
int n = nums.size();
k = k % n;
for(int i = 0; i < k; i++) {
nums.insert(nums.begin(), nums.back());
nums.pop_back();
}
}
};
optimized with extra space
class Solution {
public:
void rotate(vector<int>& nums, int k) {
int n = nums.size();
k = k%n;
vector<int> ans;
for(int i = n - k; i < n; i++) {
ans.push_back(nums[i]);
}
for(int i = 0; i < n - k; i++) {
ans.push_back(nums[i]);
}
nums = ans;
}
};
Reversal Approach
class Solution {
public:
void rotate(vector<int>& nums, int k) {
k = k%nums.size();
reverse(nums.begin(), nums.end());
reverse(nums.begin(), nums.begin()+k);
reverse(nums.begin()+k, nums.end());
}
};