739. Daily Temperatures

随声附和 提交于 2019-11-27 20:12:41

Question

739. Daily Temperatures

Solution

题目大意:比今天温度还要高还需要几天

思路:笨方法实现,每次遍历未来几天,比今天温度高,就坐标减

Java实现:

public int[] dailyTemperatures(int[] temperatures) {
    int[] ans = new int[temperatures.length];
    for (int i = 0; i<temperatures.length; i++) {
        int highIdx = i;
        for (int j=i+1; j<temperatures.length; j++) {
            if (temperatures[j] > temperatures[i]) {
                highIdx = j;
                break;
            }
        }
        ans[i] = highIdx - i;
    }
    return ans;
}

Ref

别人实现高效的方法

https://leetcode.com/problems/daily-temperatures/discuss/109832/Java-Easy-AC-Solution-with-Stack

Stack

public int[] dailyTemperatures(int[] temperatures) {
    Stack<Integer> stack = new Stack<>();
    int[] ret = new int[temperatures.length];
    for(int i = 0; i < temperatures.length; i++) {
        while(!stack.isEmpty() && temperatures[i] > temperatures[stack.peek()]) {
            int idx = stack.pop();
            ret[idx] = i - idx;
        }
        stack.push(i);
    }
    return ret;
}

Array

public int[] dailyTemperatures(int[] temperatures) {
    int[] stack = new int[temperatures.length];
    int top = -1;
    int[] ret = new int[temperatures.length];
    for(int i = 0; i < temperatures.length; i++) {
        while(top > -1 && temperatures[i] > temperatures[stack[top]]) {
            int idx = stack[top--];
            ret[idx] = i - idx;
        }
        stack[++top] = i;
    }
    return ret;
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!