1.单调栈+哈希表
class Solution {
public:
vector<int> nextGreaterElement(vector<int>& nums1, vector<int>& nums2) {
unordered_map<int,int>h;
stack<int>s;
vector<int>ans(nums1.size());
for(int i=nums2.size()-1;i>=0;i--){
while(!s.empty() && nums2[i]>=s.top()){
s.pop();
}
h[nums2[i]]=s.empty()? -1:s.top();
s.push(nums2[i]);
}
for(int i=0;i<nums1.size();i++){
ans[i]=h[nums1[i]];
}
return ans;
}
};
2.单调栈
class Solution {
public:
vector<int> dailyTemperatures(vector<int>& temperatures) {
int n = temperatures.size();
vector<int> ans(n);
stack<int> s;
for (int i = 0; i < n; ++i) {
while (!s.empty() && temperatures[i] > temperatures[s.top()]) {
int previousIndex = s.top();
ans[previousIndex] = i - previousIndex;
s.pop();
}
s.push(i);
}
return ans;
}
};
3.单调栈+循环数组
class Solution {
public:
vector<int> nextGreaterElements(vector<int>& nums) {
int n = nums.size();
vector<int> ret(n, -1);
stack<int> stk;
for (int i = 0; i < n * 2 - 1; i++) {
while (!stk.empty() && nums[stk.top()] < nums[i % n]) {
ret[stk.top()] = nums[i % n];
stk.pop();
}
stk.push(i % n);
}
return ret;
}
};