@@ -473,7 +473,7 @@ class Solution:
473
473
474
474
## 补充:单调栈
475
475
476
- 用线性的时间复杂度找左右两侧第一个大于 /小于当前元素的位置。
476
+ 顾名思义,单调栈即是栈中元素有单调性的栈,典型应用为用线性的时间复杂度找左右两侧第一个大于 /小于当前元素的位置。
477
477
478
478
### [ largest-rectangle-in-histogram] ( https://leetcode-cn.com/problems/largest-rectangle-in-histogram/ )
479
479
@@ -513,7 +513,7 @@ class Solution:
513
513
514
514
## 补充:单调队列
515
515
516
- 单调栈的拓展,可以以线性时间获得区间最大 /最小值。
516
+ 单调栈的拓展,可以从数组头 pop 出旧元素,典型应用是以线性时间获得区间最大 /最小值。
517
517
518
518
### [ sliding-window-maximum] ( https://leetcode-cn.com/problems/sliding-window-maximum/ )
519
519
@@ -533,25 +533,48 @@ class Solution:
533
533
# define a max queue
534
534
maxQ = collections.deque()
535
535
536
- def push (i ):
536
+ result = []
537
+ for i in range (N):
537
538
if maxQ and maxQ[0 ] == i - k:
538
539
maxQ.popleft()
539
540
540
541
while maxQ and nums[maxQ[- 1 ]] < nums[i]:
541
542
maxQ.pop()
542
543
543
544
maxQ.append(i)
544
- return
545
-
546
- result = []
547
- for i in range (N):
548
- push(i)
545
+
549
546
if i >= k - 1 :
550
547
result.append(nums[maxQ[0 ]])
551
548
552
549
return result
553
550
```
554
551
552
+ ### [ shortest-subarray-with-sum-at-least-k] ( https://leetcode-cn.com/problems/shortest-subarray-with-sum-at-least-k/ )
553
+
554
+ ``` Python
555
+ class Solution :
556
+ def shortestSubarray (self , A : List[int ], K : int ) -> int :
557
+ N = len (A)
558
+ cdf = [0 ]
559
+ for num in A:
560
+ cdf.append(cdf[- 1 ] + num)
561
+
562
+ result = N + 1
563
+ minQ = collections.deque()
564
+
565
+ for i, csum in enumerate (cdf):
566
+
567
+ while minQ and csum <= cdf[minQ[- 1 ]]:
568
+ minQ.pop()
569
+
570
+ while minQ and csum - cdf[minQ[0 ]] >= K:
571
+ result = min (result, i - minQ.popleft())
572
+
573
+ minQ.append(i)
574
+
575
+ return result if result < N + 1 else - 1
576
+ ```
577
+
555
578
## 总结
556
579
557
580
- 熟悉栈的使用场景
0 commit comments