您的位置:首页 > 科技 > IT业 > 力扣 739. 每日温度

力扣 739. 每日温度

2024/10/5 20:22:03 来源:https://blog.csdn.net/u010950122/article/details/139452785  浏览:    关键词:力扣 739. 每日温度

题目来源:https://leetcode.cn/problems/daily-temperatures/description/

C++题解:使用单调栈。栈里存放元素的索引,只要拿到索引就可以找到元素。

class Solution {
public:vector<int> dailyTemperatures(vector<int>& temperatures) {int len = temperatures.size();vector<int> result(len, 0);stack<int> stk;stk.push(0);for(int i = 1; i < len; i++) {if(temperatures[i] < temperatures[stk.top()]) {// 如果新元素小于栈顶的元素,把它放进栈顶,成金字塔状。stk.push(i);}else {// 如果栈顶加入了更大的元素,下面的元素就得弹出来,弹出来的时候顺便更新该位置的result,用新索引减去该位置的索引。while(!stk.empty() && temperatures[i] > temperatures[stk.top()]){result[stk.top()] = i - stk.top();stk.pop();}stk.push(i);}}// 没有更新result的元素,保持0.return result;}
};

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com