739. Daily temperature - LeetCode
Status: Violence timeout, AC after checking the idea.
By continuously maintaining a monotonically increasing stack, the answer can be obtained in one traversal. The code is as follows:
class Solution {
public:
vector<int> dailyTemperatures(vector<int>& temperatures) {
int len = temperatures.size();
vector<int> res(len, 0);
stack<int> st;
for(int i = 0; i < len; ++i){
while(!st.empty() && temperatures[st.top()] < temperatures[i]){
res[st.top()] = i - st.top();
st.pop();
}
st.push(i);
}
return res;
}
};
496. The next bigger element I - LeetCode
Status: AC after checking the train of thought.
The variation of the previous question mainly adds an unordered_map to match existing elements. The code is as follows:
class Solution {
public:
vector<int> nextGreaterElement(vector<int>& nums1, vector<int>& nums2) {
int len1 = nums1.size(), len2 = nums2.size();
vector<int> res(len1, -1);
unordered_map<int, int> unmap;
for(int i = 0; i < len1; ++i){
// key 是数组1的值,value是索引
unmap[nums1[i]] = i;
}
stack<int> st;
for(int j = 0; j < len2; ++j){
while(!st.empty() && nums2[st.top()] < nums2[j]){
if(unmap.count(nums2[st.top()]) > 0){
// nums1中存在
int index1 = unmap[nums2[st.top()]];
res[index1] = nums2[j];
}
st.pop();
}
st.push(j);
}
return res;
}
};