代码随想录算法训练营第二天|977. 有序数组的平方、209. 长度最小的子数组、 59.螺旋矩阵II
977. 有序数组的平方
【不足】
1.双指针没掌握到精髓:left = 0, right = len(nums) -1 (不是 right = 0 )
【参考资料】
【代码】
1 class Solution(object): 2 def sortedSquares(self, nums): 3 """ 4 :type nums: List[int] 5 :rtype: List[int] 6 """ 7 size = len(nums) 8 i, j, k = 0, size - 1, size - 1 9 ans = [-1] * size 10 11 while i <= j: #最后要比较两个元素 12 lm = nums[i] ** 2 13 rm = nums[j] ** 2 14 if lm > rm : 15 ans[k] = lm 16 i += 1 17 else: 18 ans[k] = rm 19 j -= 1 20 k -= 1 21 22 return ans
209. 长度最小的子数组
【精髓】
1.滑动窗口的精髓在于如何移动起始指针的位置,持续向后移动来更新滑动窗口的大小,所以要用while,而不是用if
【代码】
1 class Solution(object): 2 def minSubArrayLen(self, target, nums): 3 """ 4 :type target: int 5 :type nums: List[int] 6 :rtype: int 7 """ 8 left = 0 9 right = 0 10 size = len(nums) 11 sum = 0 12 res = float("inf") # 定义一个无限大的数 13 14 while right < size: 15 sum += nums[right] 16 17 while sum >= target: 18 subsize = right - left + 1 19 sum -= nums[left] 20 result = min(res,subsize) 21 left += 1 22 right += 1 23 24 return 0 if res == float("inf") else res
求解的时候忘记找不到这种情况了 :
return 0 if res == float("inf") else res
59. 螺旋矩阵 II
【注意】
1.循环不变量是指的对边界的处理规则: [ ) :最后一个节点不处理
【代码】
1 class Solution(object): 2 def generateMatrix(self, n): 3 """ 4 :type n: int 5 :rtype: List[List[int]] 6 """ 7 loop, mid = n//2, n//2 8 startx, starty = 0, 0 9 count = 1 10 nums = [[0] * n for _ in range(n)] #n*n的二维数组 11 12 for offset in range(1, loop+1): 13 14 for j in range(starty, n - offset): 15 nums[startx][j] = count 16 count += 1 17 for i in range(startx, n - offset): 18 nums[i][n - offset] = count 19 count += 1 20 for j in range(n - offset, starty, -1): 21 nums[n - offset][j] = count 22 count += 1 23 for i in range(n - offset, starty, -1): 24 nums[i][starty] = count 25 count += 1 26 27 startx += 1 28 starty += 1 29 30 if n % 2 == 1: 31 nums[mid][mid] = count 32 33 return nums