Given an array, rotate the array to the right by k steps, where k is non-negative.
nput:[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:
首先,k的长度超过数组长度时,其实与k%len(nums)是一样的。所以仅考虑k%len(nums)的情况
观察可以发现,结果实际上就是把原数组的后k个数放到数组的前k个数,把原数组的前n-k个放到后N-k个
class Solution:
def rotate(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: void Do not return anything, modify nums in-place instead.
"""
n = len(nums)
k = k%n
nums[:k],nums[k:] = nums[n-k:],nums[0:n-k]