题目描述:
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?
要完成的函数:
void rotate(vector<int>& nums, int k)
说明:
1、这道题给定一个vector,要求将这个vector最右边的元素调到最左边,重复这个动作k次,最终结果仍然存放在nums中。要求空间复杂度为O(1)。
2、如果只使用一个临时变量来存放的话,这意味着我们要把最后一位取出来,然后其余位往后挪,再把临时变量放在第一位。重复这个动作k次。
笔者试了一下,超时了……
所以我们使用一个长度为k的vector来存放最后那k位,空间复杂度为O(k)。
代码如下:(附详解)
void rotate(vector<int>& nums, int k)
{
int s1=nums.size();
k=k%s1;//如果nums=[1,2,3,4,5,6],k=11,我们要求余
vector<int>temp(k,0);
for(int i=0;i<k;i++)//把nums的后k位放在temp中
temp[i]=nums[s1-k+i];
for(int i=s1-k-1;i>=0;i--)//把nums的其余位往后挪k个位置
nums[i+k]=nums[i];
for(int i=0;i<k;i++)//把temp的数值放在nums的前k位
nums[i]=temp[i];
}
上述代码十分简洁,实测20ms,beats 96.80% of cpp submissions。