Skip to content

Commit b77a5b7

Browse files
committed
added a mono queue problem
1 parent de8bbe3 commit b77a5b7

File tree

1 file changed

+31
-8
lines changed

1 file changed

+31
-8
lines changed

data_structure/stack_queue.md

+31-8
Original file line numberDiff line numberDiff line change
@@ -473,7 +473,7 @@ class Solution:
473473

474474
## 补充:单调栈
475475

476-
用线性的时间复杂度找左右两侧第一个大于/小于当前元素的位置。
476+
顾名思义,单调栈即是栈中元素有单调性的栈,典型应用为用线性的时间复杂度找左右两侧第一个大于/小于当前元素的位置。
477477

478478
### [largest-rectangle-in-histogram](https://leetcode-cn.com/problems/largest-rectangle-in-histogram/)
479479

@@ -513,7 +513,7 @@ class Solution:
513513

514514
## 补充:单调队列
515515

516-
单调栈的拓展,可以以线性时间获得区间最大/最小值。
516+
单调栈的拓展,可以从数组头 pop 出旧元素,典型应用是以线性时间获得区间最大/最小值。
517517

518518
### [sliding-window-maximum](https://leetcode-cn.com/problems/sliding-window-maximum/)
519519

@@ -533,25 +533,48 @@ class Solution:
533533
# define a max queue
534534
maxQ = collections.deque()
535535

536-
def push(i):
536+
result = []
537+
for i in range(N):
537538
if maxQ and maxQ[0] == i - k:
538539
maxQ.popleft()
539540

540541
while maxQ and nums[maxQ[-1]] < nums[i]:
541542
maxQ.pop()
542543

543544
maxQ.append(i)
544-
return
545-
546-
result = []
547-
for i in range(N):
548-
push(i)
545+
549546
if i >= k - 1:
550547
result.append(nums[maxQ[0]])
551548

552549
return result
553550
```
554551

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+
555578
## 总结
556579

557580
- 熟悉栈的使用场景

0 commit comments

Comments
 (0)