力扣 862. 和至少为k的最短子数组

解法:前缀和+单调双端队列

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
def shortestSubarray(nums, k):
# 前缀和+单调双端队列
sums = [0]
for num in nums:
sums.append(num + sums[-1])

queue, ret = deque(), float("inf")
for i in range(len(sums)):
while queue and queue[-1][1] >= sums[i]:
queue.pop()

while queue and sums[i] - queue[0][1] >= k:
ret = min(ret, i - queue.popleft()[0])

queue.append((i, sums[i]))

return ret if ret != float("inf") else -1
  • Copyright: Copyright is owned by the author. For commercial reprints, please contact the author for authorization. For non-commercial reprints, please indicate the source.
  • Copyrights © 2022 eightyninth
  • Visitors:2824 | Views:3148
  • 小站在各种崩坏中坚持了: 1898天11小时31分31秒

请我喝杯咖啡吧~

支付宝
微信