给定一个数组,将数组中的元素向右移动 k 位, k 为非负整数。
输入: [1,2,3,4,5,6,7] 和 k = 3
输出: [5,6,7,1,2,3,4]
解释:
向右旋转 1 步: [7,1,2,3,4,5,6]
向右旋转 2 步: [6,7,1,2,3,4,5]
向右旋转 3 步: [5,6,7,1,2,3,4]
解答1 每次将数组向右移1位,直到移动k位
时间复杂度高,提交超出时间限制
class Solution(object):
def rotate(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: None Do not return anything, modify nums in-place instead.
"""
while k:
temp = nums[-1]
for i in range(len(nums)-1,0,-1):
nums[i] = nums[i-1]
nums[0] = temp
k = k - 1
解答2 利用数组切片
class Solution(object):
def rotate(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: None Do not return anything, modify nums in-place instead.
"""
nums[:] = nums[len(nums)-k:] + nums[:len(nums)-k]