1 题目
Given an array, rotate the array to the right by k steps, where k is non-negative.
Example 1:
Input: [1,2,3,4,5,6,7] and k = 3
Output: [5,6,7,1,2,3,4]
Explanation:
rotate 1 steps to the right: [7,1,2,3,4,5,6]
rotate 2 steps to the right: [6,7,1,2,3,4,5]
rotate 3 steps to the right: [5,6,7,1,2,3,4]
Example 2:
Input: [-1,-100,3,99] and k = 2
Output: [3,99,-1,-100]
Explanation:
rotate 1 steps to the right: [99,-1,-100,3]
rotate 2 steps to the right: [3,99,-1,-100]
Note:
- Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem.
- Could you do it in-place with O(1) extra space?
2 尝试解
2.1 分析
方法一:将末尾的元素删除,然后再添加到向量队首。重复K次即可。
方法二:数组长度为n,向右移动k位(默认k < n,否则k=k%n)。如果k是n的因子,如[1,2,3,4,5,6]向右移动两位,则数组被分为k组,每组对k取模余数相同,如[1,3,5]一组,[2,4,6]一组,每组向右挪动一位再依次叠加即可,如果n-k是k的因子,也适用,如[1,2,3,4,5,6]向右移动4位,等价于向左移动2位。如果k不是n的因子,如[1,2,3,4,5]向右移动2位,则依次挪动即可,即1挪动到3,3挪动到5,5挪动到2,2挪动到4,4挪动到1,即挪动n次得到结果,但是如果k是n的因子则会挪回原始位置,所以上面单独讨论了k或n-k是n的因子的情况。
2.2 代码
class Solution {
public:
void rotate(vector<int>& nums, int k) {
if(nums.size()==0 || k % nums.size() == 0) return ;
k = k % nums.size();
for(int i = 0; i < k; i++){
int temp = nums[nums.size()-1];
nums.erase(nums.begin()+nums.size()-1);
nums.insert(nums.begin(),temp);
}
}
};
class Solution {
public:
void rotate(vector<int>& nums, int k) {
if(nums.size() == 0 || k % nums.size() == 0) return ;
k = k % nums.size();
if(nums.size()%k != 0 && nums.size()%(nums.size()-k)!=0){
int cur = nums[k];
int pre = nums[0];
for(int i = 0; i < nums.size(); i++){
nums[(i+1)*k % nums.size()] = pre;
pre = cur;
cur = nums[(i+2)*k % nums.size()];
}
}
else{
for(int i = 0; i < (2*k > nums.size()?nums.size()-k:k); i++){
int cur = nums[k+i];
int pre = nums[i];
for(int j = 0; j < nums.size()/(2*k > nums.size()?nums.size()-k:k); j++){
nums[((j+1)*k+i)%nums.size()] = pre;
pre = cur;
cur = nums[((j+2)*k+i)%nums.size()];
}
}
}
}
};
3 标准解
void rotate(int nums[], int n, int k) {
for (; k %= n; n -= k)
for (int i = 0; i < k; i++)
swap(*nums++, nums[n - k]);
}