【python】leetcode 189. Rotate Array (easy)
阿新 • • 發佈:2018-12-12
Given an array, rotate the array to the right by k steps, where k is non-negative.
Example 1:
Input:[1,2,3,4,5,6,7]
and k = 3 Output:[5,6,7,1,2,3,4]
Explanation: rotate 1 steps to the right:[7,1,2,3,4,5,6]
rotate 2 steps to the right:[6,7,1,2,3,4,5]
rotate 3 steps to the right:[5,6,7,1,2,3,4]
Example 2:
Input:[-1,-100,3,99]
and k = 2 Output: [3,99,-1,-100] Explanation: rotate 1 steps to the right: [99,-1,-100,3] rotate 2 steps to the right: [3,99,-1,-100]Note:
- Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem.
- Could you do it in-place with O(1) extra space?
c/c++解
【待續】
python解
我能想到的最優:使用了雙端佇列collections.deque,
注意不能直接nums = list(collections.deque(nums,maxlen=len(nums)).rotate(k%len(nums)))
因為這裡list()已經是新地址了,賦給nums,nums已經不是原來的list了,題目要求in-place,即原list上修改
class Solution: def rotate(self, nums, k): """ :type nums: List[int] :type k: int :rtype: void Do not return anything, modify nums in-place instead. """ dq = collections.deque(nums,maxlen=len(nums)) dq.rotate(k%len(nums)) nums.clear() nums.extend(list(dq))
Runtime: 48 ms, faster than 99.82% of Python3
1 普通思路:末尾數字insert到開頭,並刪除末尾
但是這個方法有點慢:Runtime: 344 ms, faster than 0.98%
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.
"""
for i in range(k):
nums.insert(0,nums[-1])
del nums[-1]
2 python切片
Runtime: 68 ms, faster than 33.56%
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.
"""
length = len(nums)
nums.extend(nums[0:(length- k%length)])
del nums[0:(length - k%length)]