Given an array, rotate the array to the right by k steps, where k is non-negative.
example:
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]
code:
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.
"""
n = len(nums)
k=k%n
nums[:] = nums[n-k:] + nums[:n-k]
笔记:k=k%n是为了防止当k大于n的情况,其他的就是list的切片操作