leetcode739-每日温度

原题

根据每日 气温 列表,请重新生成一个列表,对应位置的输入是你需要再等待多久温度才会升高超过该日的天数。如果之后都不会升高,请在该位置用 0 来代替。

例如,给定一个列表 temperatures = [73, 74, 75, 71, 69, 72, 76, 73],你的输出应该是 [1, 1, 4, 2, 1, 1, 0, 0]

提示: 气温 列表长度的范围是 [1, 30000]。每个气温的值的均为华氏度,都是在 [30, 100] 范围内的整数。

解法

思想

  1. 基础栈解法:时间复杂度O(nlog n)
    将数组元素依次入栈,如果当前元素比栈首元素大则将栈首元素出栈,并知道了和栈首元素之间的距离。再次和下一个栈首元素比较,如此循环。
  2. 逆序跳跃:时间复杂度O(n)
    https://leetcode-cn.com/problems/daily-temperatures/solution/jie-ti-si-lu-by-pulsaryu/

代码

  1. 基础栈
class Node{
    public int value;
    public int pos;
    public Node(int value,int pos){
        this.value = value;
        this.pos = pos;
    }
}
class Solution {    

    public int[] dailyTemperatures(int[] T) {
        Stack<Node> stack = new Stack<>();
        int[] ans = new int[T.length];
        for(int i = 0;i<T.length;i++){
            while(!stack.empty()&&T[i]>stack.peek().value){
                Node node = stack.pop();
                ans[node.pos] = i - node.pos;
            }
            stack.push(new Node(T[i],i));
        }
        while(!stack.empty()){
            Node node = stack.pop();
            ans[node.pos] = 0;
        }

        return ans;
    }
}
  1. 逆序跳跃(作者:pulsaryu)
public int[] dailyTemperatures(int[] T) {
    int length = T.length;
    int[] result = new int[length];

    //从右向左遍历
    for (int i = length - 2; i >= 0; i--) {
        // j+= result[j]是利用已经有的结果进行跳跃
        for (int j = i + 1; j < length; j+= result[j]) {
            if (T[j] > T[i]) {
                result[i] = j - i;
                break;
            } else if (result[j] == 0) { //遇到0表示后面不会有更大的值,那当然当前值就应该也为0
                result[i] = 0;
                break;
            }
        }
    }

    return result;
}

原创文章,作者:彭晨涛,如若转载,请注明出处:https://www.codetool.top/article/leetcode739-%e6%af%8f%e6%97%a5%e6%b8%a9%e5%ba%a6/

发表回复

登录后才能评论