长度最小的子数组
长度最小的子数组
暴力解法(超时中…)
def minSubArrayLen(target: int, nums: list[int]) -> int:
result = len(nums) + 1
flag = False
for i in range(len(nums)):
sum = 0
for j in range(i,len(nums)):
sum += nums[j]
if sum >= target:
length = j - i + 1
result = min(result,length)
flag = True
return result if flag else 0
target = 11
nums = [1,1,1,1,1,1,1,1]
print(minSubArrayLen(target,nums))
滑动窗口
def minSubArrayLen(target: int, nums: list[int]) -> int:
start, end, result = 0, 0, len(nums) + 1
sum = 0
while end < len(nums):
sum += nums[end]
while sum >= target:
length = end - start + 1
result = min(result,length)
sum -= nums[start]
start += 1
end += 1
return result if result <= len(nums) else 0
s = 15
nums = [1,2,3,4,5]
print(minSubArrayLen(s,nums))
水果成篮
(超时中…)
def totalFruit(fruits: list[int]) -> int:
start, end, result = 0, 0, 0
target = []
if len(set(fruits)) <= 2:
return len(fruits)
while end < len(fruits):
target.append(fruits[end])
while len(set(target)) > 2:
result = max(result,end - start)
target.pop(0)
start += 1
end += 1
result = max(result,end - start)
return result
fruits = [0,1,2,2]
# fruits = [1,2,1]
# fruits = [1,2,3,2,2]
print(totalFruit(fruits))
题解里的另一种,不过我肯定是想不到的
def totalFruit(fruits: list[int]) -> int:
cnt = Counter()
ans = j = 0
for i, x in enumerate(fruits):
cnt[x] += 1
while len(cnt) > 2:
y = fruits[j]
cnt[y] -= 1
if cnt[y] == 0:
cnt.pop(y)
j += 1
ans = max(ans, i - j + 1)
return ans
螺旋矩阵 Ⅱ
解法来源,反正我想不到
def generateMatrix(n):
# 初始化结果矩阵
res = [[0] * n for i in range(n)]
# 维护当前值
cnt = 1
# 初始化左、右、上、下边界。
left, right, up, down = 0, n - 1, 0, n - 1
while cnt <= n * n:
# 从左到右
for i in range(left, right + 1):
res[up][i] = cnt
cnt += 1
up += 1
# 从上到下
for i in range(up, down + 1):
res[i][right] = cnt
cnt += 1
right -= 1
# 从右到左
for i in range(right, left - 1, -1):
res[down][i] = cnt
cnt += 1
down -= 1
# 从下到上
for i in range(down, up - 1, -1):
res[i][left] = cnt
cnt += 1
left += 1
return res
原文地址:https://blog.csdn.net/2303_81447590/article/details/136706577
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!