長度最小的子數組
- 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
總結
