刷力扣热题–第十八天:189:轮转数组
菜鸟第十八天开始奋战敲代码,持之以恒,见证成长
1.题目简介
2.题目解答
先用比较便捷的方法去做,即每次都向右移动1位,重复k次,时间复杂度O(M*N),空间复杂度O(1)
好的,时间复杂度太高了,那么我们直接简化k次循环,使用k个数组存储需要轮转的,其余的向后移动k位,之后在将存储的前k个元素按顺序拼接到前面,时间复杂度O(N),空间复杂度O(N)
ok,但这样空间占比还是比较高,那么我们就先翻转整个数组,再将前k个,和后len(nums)-k个进行翻转,时间复杂度O(N),空间复杂度O(1)
也过了,还不错,今天就这样~
3.心得体会
超时组
class Solution(object):
def rotate(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: None Do not return anything, modify nums in-place instead.
"""
k = k%len(nums)
while k > 0:
j = len(nums)-1
temp = nums[len(nums)-1]
while j > 0:
nums[j] = nums[j-1]
j -= 1
nums[0] = temp
k -= 1
使用额外空间组
class Solution(object):
def rotate(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: None Do not return anything, modify nums in-place instead.
"""
if k > len(nums):
k = k % len(nums)
temp = [nums[i] for i in range(len(nums)-k,len(nums))]
j = len(nums) -1
while j > k-1:
nums[j] = nums[j-k]
j -= 1
while j >= 0:
nums[j] = temp[j]
j -= 1
数组翻转
class Solution(object):
def rotate(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: None Do not return anything, modify nums in-place instead.
"""
k = k%len(nums)
def revese(nums,start,end):
while start < end:
temp = nums[start]
nums[start] = nums[end]
nums[end] = temp
start += 1
end -= 1
return nums
revese(nums,0,len(nums)-1)
revese(nums,0,k-1)
revese(nums,k,len(nums)-1)
4.做题时长
7月23日 14:30-15:00