739. 每日温度 (单调栈)

739. 每日温度

1、暴力解法

var dailyTemperatures = function(temperatures) {
    const res = [],len = temperatures.length;
    
    for(let i=0; i<len; i++){
        for(let j=i+1;j<len;j++){
            // 找到大于的树,计算距离返回
            if(temperatures[i] < temperatures[j]){
                res.push(j-i)
                break
            }else if(temperatures[i] >= temperatures[j] && j == len-1){
                res.push(0)
            }
        }
    }
    res.push(0)
    return res
};

2、单调栈

通常是一维数组,要寻找任一个元素的右边或者左边第一个比自己大或者小的元素的位置,可以用单调栈。

var dailyTemperatures = function(temperatures) {
    const n = temperatures.length;
    const res = Array(n).fill(0);
    const stack = [];  // 递增栈:用于存储元素右面第一个比他大的元素下标
    stack.push(0);
    for (let i = 1; i < n; i++) {
        // 栈顶元素,就是当前检查元素
        const top = stack[stack.length - 1];

        // 向后依次比较
        if (temperatures[i] < temperatures[top]) {
            stack.push(i);
        } else if (temperatures[i] === temperatures[top]) {
            stack.push(i);
        } else {
            while (stack.length && temperatures[i] > temperatures[stack[stack.length - 1]]) {
                const top = stack.pop();
                // 找到比当前值大的数,存放距离
                res[top] = i - top;
            }
            stack.push(i);
        }
    }
    return res;
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值