https://leetcode.com/problems/next-greater-element-i/description/
题目:求出数组一中每个元素在第二个数组中对应位置的元素比它大的第一个数。
思路:单调栈(维护一个单调递增的栈,每次找到一个比栈顶元素大的元素,就将栈顶元素出栈,记录比栈顶元素大的元素的值,最后栈中元素比它大的元素都为-1)。
代码
class Solution {
public:
vector<int> nextGreaterElement(vector<int>& findNums, vector<int>& nums) {
int len1=findNums.size(),len2=nums.size();
map<int,int>m;
vector<int>v;
stack<int>s;
for(int x=0;x<len2;x++){
while(!s.empty()&&s.top()<nums[x]){
m[s.top()] = nums[x];
s.pop();
}
s.push(nums[x]);
}
while(!s.empty()) {
m[s.top()] = -1;
s.pop();
}
for(int num : findNums){
v.push_back(m[num]);
}
return v;
}
};
简化版:
class Solution {
public:
vector<int> nextGreaterElement(vector<int>& findNums, vector<int>& nums) {
int len1=findNums.size(),len2=nums.size();
map<int,int>m;
vector<int>v;
stack<int>s;
for(int x=0;x<len2;x++){
while(!s.empty()&&s.top()<nums[x]){
m[s.top()] = nums[x];
s.pop();
}
s.push(nums[x]);
}
for(int num : findNums){
v.push_back(m.count(num)==0?-1:m[num]);
}
return v;
}
};