前两个自刷时学了,但是实话说还是很难自己想起来双指针法,但是代码瞥一眼,会思路了代码一次ac,昨天海康笔试也是,那个编程看见答案才发现这么简单……我完全也会,但是为什么拿到题的时候很难自己产生思路?
思路是根据输入的特点,大的肯定是最左或最右。于是左右各一个指针,比较平方值,大的往后放。
class Solution:
def sortedSquares(self, nums: List[int]) -> List[int]:
i = 0
j = len(nums)-1
nums_sort = [0]*len(nums)
sort_index = len(nums)-1
while i<=j:
if nums[i]*nums[i]>=nums[j]*nums[j]:
nums_sort[sort_index] = nums[i]*nums[i]
i += 1
sort_index -= 1
else :
nums_sort[sort_index] = nums[j]*nums[j]
j -= 1
sort_index -= 1
return nums_sort
这个滑动窗口,我自己刷的时候就debug了好久……二刷又在dubug……逻辑一看就懂,代码一写就错……
class Solution:
def minSubArrayLen(self, s: int, nums: List[int]) -> int:
i = 0
j = 0#j的初始赋值要想好
sum_stack = nums[0]
len_out = -1
while i <= j and j < len(nums):
if sum_stack < s:
j += 1
if j < len(nums):#因为这里有+1的操作所以需要判断j会不会超出边界
sum_stack += nums[j]
else:
if len_out != -1:
len_out = min( len_out,j - i+1)#数组长度的求法要不要加减1,要仔细考虑
else: # 第一次赋值
len_out = j - i+1
sum_stack -= nums[i]
i += 1
return 0 if len_out == -1 else len_out
又仔细看了一遍卡哥给出的代码,明天再做一遍。又是一场酣畅淋漓的while……比卡哥给出的复杂很多……
螺旋数组自刷的时候没看,因为感觉就是一个固定位置坐标的限制……没什么技术含量,比较简单
class Solution:
def generateMatrix(self, n: int) -> List[List[int]]:
matrix = [[0]*n for _ in range(n)]#初始化矩阵,俩中括号是二维矩阵
top,bottom,left,right = 0,n-1,0,n-1#赋值边界
count = 1
while top<bottom and left<right:
for i in range(left,right):#上填充
matrix[top][i] = count
count += 1
for i in range(top,bottom):#右填充
matrix[i][right] = count
count += 1
for i in range(right,left,-1):#下填充
matrix[bottom][i] = count
count += 1
for i in range(bottom,top,-1):#上填充
matrix[i][left] = count
count += 1
top += 1
bottom -= 1
left += 1
right -= 1
if count==n*n:#n为奇数,中心值未被赋值的情况
matrix[n//2][n//2] = count
return matrix
这种限定边界的比较符合我的思考逻辑,另一种做法感觉太复杂了