Description
Rotate an array of n elements to the right by k steps.
For example, with n = 7 and k = 3, the array [1,2,3,4,5,6,7]
is rotated to [5,6,7,1,2,3,4]
.
Analysis
本题即循环右移。要记得将移位数k
对n
取余,即
k=kmodn
否则会多作无用功。
解法一:新建
vector<int> result[n]
,按右移后顺序填充数组,再赋给
nums
。
解法二:本地插入删除,将
nums[n-k]~nums[n-1]
的所有元素,插入到
nums
开头,然后删除最后的歌
k
个元素。
Code
Version 1
class Solution {
public:
void rotate(vector<int>& nums, int k) {
int n = nums.size();
k %= n;
vector<int> result(n);
int i = 0;
int j = n - k;
while (j < n)
result[i++] = nums[j++];
j = 0;
while (i < n)
result[i++] = nums[j++];
nums = result;
}
};
Version 2
class Solution {
public:
void rotate(vector<int>& nums, int k) {
k %= nums.size();
nums.insert(nums.begin(), nums.end() - k, nums.end());
nums.erase(nums.end() - k, nums.end());
}
};
Appendix
- Link: https://leetcode.com/problems/rotate-array/
- Run Time:
- Version 1: 22ms
- Version 2: 23ms
- My first submission in Discussion…
Link: https://discuss.leetcode.com/topic/85266/3-line-c-solution-using-insert-and-erase