LeetCode 739. Daily Temperatures. tags: 单调栈。 中等难度

Given an array of integers temperatures represents the daily temperatures, return an array answer such that answer[i] is the number of days you have to wait after the ith day to get a warmer temperature. If there is no future day for which this is possible, keep answer[i] == 0 instead.

Example 1:

Input: temperatures = [73,74,75,71,69,72,76,73]
Output: [1,1,4,2,1,1,0,0]
Example 2:

Input: temperatures = [30,40,50,60]
Output: [1,1,1,0]
Example 3:

Input: temperatures = [30,60,90]
Output: [1,1,0]
 

Constraints:

1 <= temperatures.length <= 105
30 <= temperatures[i] <= 100

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/daily-temperatures
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

我的解答:

// 单调栈法, 栈里只能存比栈顶更小的,那相等呢
class Solution {
public:
    vector<int> dailyTemperatures(vector<int>& temperatures) {
        int len = temperatures.size();

        // 存数组temperatures的索引
        stack<int> myStack;
        vector<int> answers(len, 0); // 最后一个,一定是0
        int top;
        for(int i = 0; i < len; i ++){  //不是i<len,因为最后一个元素会影响前边的结果
            if( myStack.empty() )  {
                myStack.push(i);
                continue;
            }else{
                // if(!myStack.empty())  
                top = myStack.top();
                if(temperatures[i] > temperatures[top]){
                    while(!myStack.empty() && temperatures[i] > temperatures[top]){
                        answers[top] = i - top;
                        myStack.pop();
                        if(!myStack.empty()) top = myStack.top();
                    }
                    myStack.push(i);
                }else{   // 后边温度更小,?或者相等
                    myStack.push(i);
                }
            }

        }
        return answers;

    }
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值