长度最小的子数组
- https://leetcode.cn/problems/minimum-size-subarray-sum/

思路
- 使用
滑动窗口
,left
表示滑动窗口的起始点
,right
表示滑动窗口的终点
class Solution:def minSubArrayLen(self, target: int, nums: List[int]) -> int:left = 0 res = float('inf') total = 0 length = len(nums)for right in range(length): total += nums[right]while total >= target:l = right - left + 1res = min(l, res)total -= nums[left]left += 1if res == float('inf'): return 0else: return res
螺旋矩阵
- https://leetcode.cn/problems/spiral-matrix-ii/

思路
每遍历一条边
时,保持循环不变量原则
,即每一条边都遵循左闭右开[)
的原则
class Solution:def generateMatrix(self, n: int) -> List[List[int]]:arr = [ [None]*n for _ in range(n)] startx, starty = 0, 0 offset = 1 count = 1 loop = n // 2 mid = n // 2 while loop > 0:for y in range(starty, n - offset): arr[startx][y] = countcount+=1for x in range(startx, n - offset): arr[x][n - offset] = countcount+=1for y in range(n - offset, starty, -1): arr[n - offset][y] = countcount+=1for x in range(n - offset, startx, -1): arr[x][starty] = countcount+=1startx += 1starty += 1offset += 1loop -= 1if n%2 == 1: arr[mid][mid] = n*nreturn arr
总结
