思路:一开始用暴力算法解出来了,看了代码随想录的思路,用双指针解了,妙啊
时间复杂度:O(n)
空间复杂度:O(n)
class Solution(object):
def sortedSquares(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
left=0
right=len(nums)-1
i=len(nums)-1
result=[0]*len(nums)
while left<=right:
if abs(nums[left])<=nums[right]:
result[i]=nums[right]*nums[right]
right-=1
else:
result[i]=nums[left]*nums[left]
left+=1
i-=1
return result
思路:滑动窗口实现。本质还是利用双指针,当窗口内值大于等于目标值时,左指针加1,循环判断窗口内值是否大于等于目标值,直到左右指针窗口内的值和小于目标值,此时右指针加1
注意:最后返回值的确定 如果有满足条件的结果,返回 若无满足条件的,返回0
时间复杂度:O(n)
class Solution(object):
def minSubArrayLen(self, target, nums):
"""
:type target: int
:type nums: List[int]
:rtype: int
"""
left=0
right=0
result=float("inf")
curr_sum=0
while right<len(nums):
curr_sum+=nums[right]
while curr_sum>=target:
result=min(result,right-left+1)
curr_sum-=nums[left]
left+=1
right+=1
return result if result!=float('inf') else 0
思路:因为这道题之前已经听过讲解,思路还记得。记得思路是一回事,实现又是另一回事。debug挺久的
时间复杂度:O(n)
class Solution(object):
def generateMatrix(self, n):
"""
:type n: int
:rtype: List[List[int]]
"""
stx=0
sty=0
offset=n-1
loop=n//2
mid=n//2
result=[[0]*n for _ in range(n)]
s=1
for offset in range(1,loop+1):
for j in range(sty,n-offset):
result[stx][j]=s
s+=1
for i in range(stx,n-offset):
result[i][n-offset]=s
s+=1
for j in range(n-offset,sty,-1):
result[n-offset][j]=s
s+=1
for i in range(n-offset,stx,-1):
result[i][sty]=s
s+=1
stx+=1
sty+=1
if n%2!=0:
result[mid][mid]=s
return result