add monotonic_stack_queue url

This commit is contained in:
ShusenTang 2020-03-12 22:58:56 +08:00
parent f44a014ca3
commit e19bb7d5f6

View File

@ -1,11 +1,16 @@
# [496. Next Greater Element I](https://leetcode.com/problems/next-greater-element-i/description/)
# 思路
这题暴力法的时间复杂度为O(n^2)。下面介绍更快的方法:
从前往后遍历nums用一个栈s记录此时还没找到Next-Greater-Element的元素操作分两步
# 思路、单调栈
这题暴力法的时间复杂度为O(n^2)。
但其实这题其实是单调栈的典型应用,关于单调栈可以参考[我的总结](../algorithm/array/monotonic_stack_queue.md)。
我们从前往后遍历nums用一个栈s记录此时还没找到Next-Greater-Element的元素操作分两步
* 1、若当前的元素n比s.top大就将栈顶pop出来(s.top的Next-Greater-Element就为n)循环直到元素n小于栈顶或者栈空
* 2、将n进栈
所以栈里的元素肯定是自底向上递减的例如若nums=[1 6 5 3 4]则当遍历到3时栈s为[6,5]而3 < s.top() = 5所以直到此时依然没有找到5的Next-Greater-Element即5不应该pop出来遍历到4时s为[653]而4 > s.top() = 3, 所以3的Next-Greater-Element找到了应该将其pop出来然后4 < s.top() = 5所以5不应该pop
时间复杂度O(n)
# C++
```C++