黔西南建设厅网站,图片设计用什么软件,巩义企业网站建设报价,国内外贸平台目录
739. 每日温度
496.下一个更大元素 I 739. 每日温度
题目链接#xff1a;739. 每日温度
求某数右边最近的大于自己的数#xff0c;采用单调栈的方法。日期早的数先进栈#xff0c;每次遍历到某一天就将该天温度依次与栈中各天温度进行比较#xff0c;若大于栈中温…目录
739. 每日温度
496.下一个更大元素 I 739. 每日温度
题目链接739. 每日温度
求某数右边最近的大于自己的数采用单调栈的方法。日期早的数先进栈每次遍历到某一天就将该天温度依次与栈中各天温度进行比较若大于栈中温度则该天即为栈中天的最近大于自己温度的那天。
class Solution {
public:vectorint dailyTemperatures(vectorint temperatures) {vectorint ans(temperatures.size(), 0);stackint st;st.push(0);for(int i 1; i temperatures.size(); i){while(!st.empty() temperatures[st.top()] temperatures[i]){ans[st.top()] i - st.top();st.pop();}st.push(i);}return ans;}
};
496.下一个更大元素 I
题目链接496. 下一个更大元素 I
最开始的思路是想只针对 nums1 中的各个数来求其下一个更大的元素可能会存在很多重复计算如果还是使用单调栈来实现这一题那么其实是针对 nums2 中的每一个元素都求出其下一个更大的元素再针对 nums1 中这些数的位置进行结果输出。
class Solution {
public:vectorint nextGreaterElement(vectorint nums1, vectorint nums2) {vectorint ans(nums1.size(), -1);unordered_mapint, int umap;for(int i 0; i nums1.size(); i){umap[nums1[i]] i;}stackint st;st.push(0);for(int i 0; i nums2.size(); i){while(!st.empty() nums2[st.top()] nums2[i]){if(umap.count(nums2[st.top()]) 0){ans[umap[nums2[st.top()]]] nums2[i];}st.pop();}st.push(i);}return ans;}
};