977.无序数组的平方
1.暴力解法
class Solution(object):
def sortedSquares(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
size=len(nums)
for i in range(size):
nums[i]=nums[i]**2
nums.sort()
return nums
2.双指针法
class Solution(object):
def sortedSquares(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
left,right,i=0,len(nums)-1,len(nums)-1
res=[float("inf")]*len(nums)
while left<=right:
if nums[left]**2<nums[right]**2:
res[i]=nums[right]**2
right-=1
else:
res[i]=nums[left]**2
left+=1
i-=1
return res
209.长度最小的子数组
1.滑动窗口
class Solution(object):
def minSubArrayLen(self, target, nums):
"""
:type target: int
:type nums: List[int]
:rtype: int
"""
size=len(nums)
left=0
right=0
min_len=float("inf")
cur_sum=0
while right<size:
cur_sum+=nums[right]
while cur_sum>=target:
min_len=min(min_len,right-left+1)
cur_sum-=nums[left]
left+=1
right+=1
if min_len!=float("inf"):
return min_len
else:
return 0
2.暴力解法
class Solution(object):
def minSubArrayLen(self, target, nums):
"""
:type target: int
:type nums: List[int]
:rtype: int
"""
size=len(nums)
min_len=float("inf")
for i in range(size):
cur_num=0
for j in range(i,size):
cur_num+=nums[j]
if cur_num>=target:
min_len=min(min_len,j-i+1)
if min_len!=float("inf"):
return min_len
else:
return 0
暴力解法会超出时间限制
59.螺旋矩阵II
二分法
class Solution(object):
def generateMatrix(self, n):
"""
:type n: int
:rtype: List[List[int]]
"""
nums = [[0] * n for _ in range(n)]
startx, starty = 0, 0 # 起始点
loop, mid = n // 2, n // 2 # 迭代次数、n为奇数时,矩阵的中心点
count = 1 # 计数
for offset in range(1, loop + 1) : # 每循环一层偏移量加1,偏移量从1开始
for i in range(starty, n - offset) : # 从左至右,左闭右开
nums[startx][i] = count
count += 1
for i in range(startx, n - offset) : # 从上至下
nums[i][n - offset] = count
count += 1
for i in range(n - offset, starty, -1) : # 从右至左
nums[n - offset][i] = count
count += 1
for i in range(n - offset, startx, -1) : # 从下至上
nums[i][starty] = count
count += 1
startx += 1 # 更新起始点
starty += 1
if n % 2 != 0 : # n为奇数时,填充中心点
nums[mid][mid] = count
return nums