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)]