739. Daily Temperatures - LeetCode

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;
}
posted @ 2018-07-29 23:31  okokabcd  阅读(193)  评论(0编辑  收藏  举报