题目:旋转数组
给定一个数组,将数组中的元素向右移动 k 个位置,其中 k 是非负数。
示例 :
输入: [1,2,3,4,5,6,7] 和 k = 3,输出: [5,6,7,1,2,3,4]
输入: [-1,-100,3,99] 和 k = 2,输出: [3,99,-1,-100]
说明:
尽可能想出更多的解决方案,至少有三种不同的方法可以解决这个问题。
要求使用空间复杂度为 O(1) 的 原地 算法。
---------------------------------------------------------------------------
解法1:切片拼接法。缺点是空间复杂度太高。
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.
"""
# 切片拼接的方式, 空间复杂度高
l = len(nums)
nums[:] = nums[l-k:] + nums[:l-k]
解法2:每次循环在list尾部删除一个,同时在头部加入一个。
注意:pop()方法可以接收被删除的元素。
pop() 函数用于移除列表中的一个元素(默认最后一个元素),并且返回该元素的值。
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):
last = nums.pop()
nums.insert(0, last)
解法3:巧妙的使用数学符号 %。
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[:] = nums[-(k % len(nums)):] + nums[:-(k % len(nums))]
print(nums)
参考:
https://www.runoob.com/python/att-list-pop.html
https://blog.youkuaiyun.com/huhehaotechangsha/article/details/80467219
https://blog.youkuaiyun.com/qq_36190978/article/details/86757046