题目:
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?
解释:
解法1:
每次保存最后一个元素,移动之前所有的元素,再把最后一个元素给第一个元素,这样效率非常低,会TLE
解法2:
k>n 时,不断循环更新:k=k-n
k=n-k-1
(不断是不是k>n,都要做这个操作)
step 1 reversenums[:k+1]
step 2 reversenums[k+1:]
step 3 reverse总数组
解法3:
step 1 reverse原来的数组
step 2 reverse 0~ k-1nums[:k]
step 3 reverse k ~ n-1num[k:]
相比之下感觉解法3更好理解,因为不需要对k做太多变换…
python不能直接用切片和[::-1]
,反正用了以后,nums
吧,所以还是自己手动实现一个reverse()
吧。
解法3,python代码:
class Solution(object):
def rotate(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: void Do not return anything, modify nums in-place instead.
"""
def reverse(low,high,nums):
while low<high:
nums[low],nums[high]=nums[high],nums[low]
low+=1
high-=1
n=len(nums)
k%=n;
reverse(0,n-1,nums)
reverse(0,k-1,nums)
reverse(k,n-1,nums)
解法3,c++代码:
#include <algorithm>
class Solution {
public:
void rotate(vector<int>& nums, int k) {
int n=nums.size();
k%=n;
//这种解法更好记,界限是k,之前的不仅要改变k,界限还是k+1
reverse(nums.begin(),nums.end());
reverse(nums.begin(),nums.begin()+k);
reverse(nums.begin()+k,nums.end());
}
};
总结:
数组的旋转也是一个系列题目呢。
关于数组rotate的一般规律:
向左移动:先分别翻转两部分,再全部翻转
向右移动:先全部翻转,再分别翻转两部分
其中左半部分是nums[:k]
,右半部分是nums[k:]