739. 每日温度
class Solution {
public:
vector<int> dailyTemperatures(vector<int>& temperatures) {
int n = temperatures.size();
stack<int> sta;
vector<int> res(n, 0);
sta.push(0);
for (int i = 0; i < n; i ++)
{
while (!sta.empty() && temperatures[i] > temperatures[sta.top()])
{
res[sta.top()] = i - sta.top();
sta.pop();
}
sta.push(i);
}
return res;
}
};
496. 下一个更大元素 I
用一个哈希表记录 nums1 的数字和下标的关系
class Solution {
public:
vector<int> nextGreaterElement(vector<int>& nums1, vector<int>& nums2) {
if (nums1.size() == 0) return {};
unordered_map<int, int> umap; // (val, idx)
stack<int> sta;
vector<int> res(nums1.size(), -1);
for (int i = 0; i < nums1.size(); i ++)
umap[nums1[i]] = i;
sta.push(0);
for (int i = 1; i < nums2.size(); i ++)
{
while (sta.size() && nums2[i] > nums2[sta.top()])
{
if (umap.count(nums2[sta.top()]))
{
int idx = umap[nums2[sta.top()]];
res[idx] = nums2[i];
}
sta.pop();
}
sta.push(i);
}
return res;
}
};