题目:
将包含 n 个元素的数组向右旋转 k 步。
例如,如果 n = 7 , k = 3,给定数组 [1,2,3,4,5,6,7] ,向右旋转后的结果为 [5,6,7,1,2,3,4]。
要求:
要求空间复杂度为 O(1)
(这里的意思就是别想着新建个列表)
解决方法一:
简单暴力点,将后面k个删掉插入到前面。
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.
"""
lenth = len(nums) - 1
if lenth < 1 or k < 1:
return
for i in range (k):
nums.insert(0, nums[lenth])
del nums[lenth + 1]
return nums #leetcode不需要这一行,这里为了打印效果添加的
ls = [1,2]
print(Solution().rotate(ls,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.
"""
lenth = len(nums) - 1
if lenth < 1 or k < 1:
print("Input list is less than 2 no need to rotate, or num k is invalid")
return
for i in range (k):
nums[:] = [nums[lenth]] + nums[:lenth]
return nums
ls = [1,2]
print(Solution().rotate(ls,2))
看起来优雅了一些,但是实际运行效率还不如第一种,哭,继续……
解决方法三:
看到有人用reverse,这个想法很巧妙,具体如下:
举一个例子:
1 2 3 4 5 6 7 如果k = 3 的话, 会变成 5 6 7 1 2 3 4
7 6 5 4 3 2 1 先翻转整个数组
5 6 7 4 3 2 1 翻转前k个数字
5 6 7 1 2 3 4 翻转后面几个数字
不过比较适用于长list,对于短list优点抓瞎,那就结合一下吧
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.
"""
lenth = len(nums) - 1
if lenth < 1 or k < 1:
print("Input list is less than 2 no need to rotate, or num k is invalid")
return
if (k < lenth):
nums.reverse()
nums[0:k] = reversed(nums[0:k])
nums[k:] = reversed(nums[k:])
else:
for i in range (k):
nums.insert(0, nums[lenth])
del nums[lenth + 1]
return nums
ls = [1,2]
print(Solution().rotate(ls,1))
代码长了点,但是效率不错!