2018-10-18 06:23:23 +00:00
|
|
|
|
# [496. Next Greater Element I](https://leetcode.com/problems/next-greater-element-i/description/)
|
2020-03-12 14:58:56 +00:00
|
|
|
|
|
|
|
|
|
# 思路、单调栈
|
|
|
|
|
这题暴力法的时间复杂度为O(n^2)。
|
|
|
|
|
|
|
|
|
|
但其实这题其实是单调栈的典型应用,关于单调栈可以参考[我的总结](../algorithm/array/monotonic_stack_queue.md)。
|
|
|
|
|
|
|
|
|
|
我们从前往后遍历nums,用一个栈s记录此时还没找到Next-Greater-Element的元素,操作分两步:
|
2018-10-18 06:23:23 +00:00
|
|
|
|
* 1、若当前的元素n比s.top大就将栈顶pop出来(s.top的Next-Greater-Element就为n),循环直到元素n小于栈顶或者栈空;
|
|
|
|
|
* 2、将n进栈;
|
|
|
|
|
|
2020-03-12 14:58:56 +00:00
|
|
|
|
所以栈里的元素肯定是自底向上递减的,例如若nums=[1 6 5 3 4],则当遍历到3时,栈s为[6,5],而3 < s.top() = 5所以直到此时依然没有找到5的Next-Greater-Element,即5不应该pop出来。遍历到4时,s为[6,5,3],而4 > s.top() = 3, 所以3的Next-Greater-Element找到了,应该将其pop出来,然后4 < s.top() = 5,所以5不应该pop。
|
|
|
|
|
|
2018-10-18 06:24:57 +00:00
|
|
|
|
时间复杂度O(n)
|
2018-10-18 06:23:23 +00:00
|
|
|
|
# C++
|
2019-09-13 15:08:41 +00:00
|
|
|
|
```C++
|
2018-10-18 06:23:23 +00:00
|
|
|
|
class Solution {
|
|
|
|
|
public:
|
|
|
|
|
vector<int> nextGreaterElement(vector<int>& findNums, vector<int>& nums) {
|
|
|
|
|
stack<int> s;
|
|
|
|
|
unordered_map<int, int> mp; // 用hash记录元素的Next-Greater-Element
|
|
|
|
|
for (int n : nums) {
|
|
|
|
|
while (s.size() && s.top() < n) { // s.top() < n时, s.top()的Next-Greater-Element就是n
|
|
|
|
|
mp[s.top()] = n;
|
|
|
|
|
s.pop(); // 栈顶元素的Next-Greater-Element找到了,所以应该将栈顶pop出来
|
|
|
|
|
}
|
|
|
|
|
s.push(n); // 栈里的元素始终是自底向上递减的
|
|
|
|
|
}
|
|
|
|
|
vector<int> res;
|
|
|
|
|
for (int n : findNums) res.push_back(mp.count(n) ? mp[n] : -1);
|
|
|
|
|
return res;
|
|
|
|
|
}
|
|
|
|
|
};
|
|
|
|
|
```
|