题目:
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].
Note:
Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem.
注意:
尽量想出三种方法。
方法一:性能238ms
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.
"""
while k > 0:
nums.insert(0,nums.pop())
k -= 1
方法二:性能75ms
class Solution(object):
def rotate(self, nums, k):
nums_copy = nums[:]
l = len(nums)
for i, n in enumerate(nums_copy):
nums[(i + k) % l] = n
方法三:性能66ms
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.
"""
nums.reverse()
k%=len(nums)
nums[:k]=nums[:k][::-1]
nums[k:]=nums[k:][::-1]