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.
此题不难,这里给出两种方法:
方法1:列表元素从后向前,一个个取出,不断插入最前面,插入 k 个即可。见 Python 实现 rotate 函数。
方法2:使用Python的切片,把后k个元素放到前面即可。见 Python 实现 rotate2 函数。
将一个列表(如 a = [1,2,3])作为参数传入函数,如果在函数中执行 a = [4,5,6], a会在函数中改变,但是出了函数 a并没有改变(还是 [1,2,3])。如果想要 a 出了函数也改变,应该使用 a[:] = [4,5,6]。
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) - 1
while k > 0:
num = nums.pop()
nums.insert(0, num)
n -= 1; k-= 1
# return nums
def rotate2(self, nums, k):
n = len(nums) - k
# 注意,应该使用 nums[:] 而不是 nums,前者可以真正改变传入的nums列表,而后者不可以
nums[:] = nums[n:] + nums[:n]
# return nums
a = [1,2,3,4,5,6,7]
k = 3
b = Solution()
print(b.rotate(a[:], k)) # [5,6,7,1,2,3,4]
print(b.rotate2(a, k)) # [5,6,7,1,2,3,4]
print(a) # [5,6,7,1,2,3,4]