977
解法1:暴力解法
class Solution:
def sortedSquares(self, nums: List[int]) -> List[int]:
for i in range(len(nums)):
nums[i]=nums[i]*nums[i]
nums.sort()
return nums
解法2:双指针
class Solution:
def sortedSquares(self, nums: List[int]) -> List[int]:
n=len(nums)
i=0
j=n-1
res=[0]*n
k=n-1
while i<=j:
print(i,j,k)
print(nums[i],nums[j])
if nums[i]*nums[i]<=nums[j]*nums[j]:
res[k]=nums[j]*nums[j]
j-=1
k-=1
else:
res[k]=nums[i]*nums[i]
k-=1
i+=1
return res
感想:
1.平方后数组中的数值大小趋势是:从外到内数值在减小,最小的值是在中间的,最大的值一定是在两端的。
2.由于从小到大排序,但是数值大小的判断是从大到小,所以新数组是从最后一位数字逐步向前确定的
209
解法1:暴力解
class Solution:
def minSubArrayLen(self, target: int, nums: List[int]) -> int:
n=len(nums)
res=n+1
for i in range(n):
cur_sum=0
for j in range(i,n):
cur_sum+=nums[j]
if cur_sum>=target:
res=min(res,j-i+1)
break
if res==n+1:
return 0
else:
return res
解法2:滑动窗口
class Solution:
def minSubArrayLen(self, target: int, nums: List[int]) -> int:
n=len(nums)
left=0
right=0
res=float('inf')
cur_sum=0
while right<n:
cur_sum+=nums[right]
while cur_sum>=target:
res=min(res,right-left+1)
cur_sum-=nums[left]
left+=1
right+=1
if res==float('inf'):
return 0
else:
return res
感想:使用滑动窗口重点注意如何移动起始位置,这里是当数组中的总和大于目标值时开始移动。
59
class Solution:
def generateMatrix(self, n: int) -> List[List[int]]:
nums=[[0]*n for i in range(n)]
x=0
y=0
count=1
loop,mid=n//2,n//2
for i in range(0,loop):
for j in range(y,n-i-1):
nums[i][j]=count
count+=1
print(nums)
for j in range(x,n-i-1):
nums[j][n-i-1]=count
count+=1
print(nums)
for j in range(n-i-1,y,-1):
nums[n-i-1][j]=count
count+=1
print(nums)
for j in range(n-i-1,x,-1):
print(i,j)
nums[j][i]=count
count+=1
print(nums)
x+=1
y+=1
if n%2!=0:
nums[mid][mid]=count
return nums
感想:注意边界,左闭右开