defshortestSubarray(nums, k): # 前缀和+单调双端队列 sums = [0] for num in nums: sums.append(num + sums[-1]) queue, ret = deque(), float("inf") for i inrange(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.