给定一个数组,将数组中的元素向右移动 k 个位置,其中 k 是非负数。
方案一:拼接
def rotate(nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: void Do not return anything, modify nums in-place instead.
"""
t = k % len(nums)
nums[:] = nums[-t:] + nums[: -t]
#nums[:] = nums[len(nums) - t:] + nums[: len(nums) - t]
return
方案二:利用列表的方法,尾增首删
def rotate(nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: void Do not return anything, modify nums in-place instead.
"""
for _ in range(k % len(nums):
nums.insert(0, nums[-1])
nums.pop()
return
方案三:替换元素
def rotate(nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: void Do not return anything, modify nums in-place instead.
"""
a = nums[:]
if len(nums) == 1 or len(nums) == k or k == 0:
nums
else:
for i in range(len(nums)):
nums[(i + k) % len(nums)] = a[i]