总结:今日事单调栈的开端,还是挺巧妙的。
代码:
cpp
class Solution {
public:
vector<int> nextGreaterElement(vector<int>& nums1, vector<int>& nums2) {
vector<int> res(nums1.size(),-1);
unordered_map<int,int> umap;
if(nums1.size() == 0)
return res;
for(int i = 0; i < nums1.size();i++)
umap[nums1[i]] = i;
stack<int> st;
st.push(0);
for(int i = 1;i < nums2.size();i++)
{
if(nums2[i] <= nums2[st.top()])
st.push(i);
else
{
while(!st.empty() && nums2[i] > nums2[st.top()])
{
if(umap.count(nums2[st.top()]) > 0)
{
int index = umap[nums2[st.top()]];
res[index] = nums2[i];
}
st.pop();
}
st.push(i);
}
}
return res;
}
};
cpp
class Solution {
public:
vector<int> dailyTemperatures(vector<int>& temperatures) {
stack<int> st;
vector<int> res(temperatures.size(),0);
st.push(0);
for(int i = 1;i < temperatures.size();i++)
{
if(temperatures[i] <= temperatures[st.top()])
st.push(i);
else
{
while(!st.empty() && temperatures[i] > temperatures[st.top()])
{
res[st.top()] = i - st.top();
st.pop();
}
st.push(i);
}
}
return res;
}
};