# sumOfnums = sum(nums) slow = 0 L = len(nums) res = float('inf')
# if sumOfnums < target: # return 0
newSum = 0
# 循环pop for fast inrange(L): newSum += nums[fast]
while newSum >= target: res = min(res, fast - slow + 1) newSum -= nums[slow] slow += 1 # newSum在减掉nums[slow]后,不一定会再大于target,不需要再将res-1 # res -= 1 # 通过让res与inf比较,从而得知是否存在长度最小的子数组满足条件,否则就返回0; # 这样的好处是不需要对整个数组求和 if res != float('inf'): return res return0
loop, mid = n//2, n//2#迭代次数,n为奇数时,矩阵的中心点 index = 1 startx, starty = 0, 0 nums = [[0] * n for _ inrange(n)] for offset inrange(1, loop + 1): # 第一行 for i inrange(starty, n - offset): nums[startx][i] = index index += 1 # 最后一列 for j inrange(startx, n - offset): nums[j][n - offset] = index index += 1 # 最后一行 for i inrange(n - offset, starty, -1): nums[n - offset][i] = index index += 1 # 第一列 for j inrange(n - offset, startx, -1): nums[j][starty] = index index += 1 startx += 1 starty += 1 if n % 2 != 0: nums[mid][mid] = index return nums