Rotate an array of
n elements to the right by
k steps.
For example, with n = 7 and k = 3, the array [1,2,3,4,5,6,7]
is rotated to [5,6,7,1,2,3,4]
.
Hint:
Could you do it in-place with O(1) extra space?
Could you do it in-place with O(1) extra space?
题目大意:旋转一个列表,要求空间复杂度O(1)。
思路:使用Python list 的切片
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 %= n
nums[:] = nums[n-k:] + nums[:n-k]
nums[:]的作用见这里