其他分享
首页 > 其他分享> > 739. Daily Temperatures

739. Daily Temperatures

作者:互联网

I firstly solved this problem bruteforcely, the solution is easy, but the time complexity is O(n2):

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

Then I studied monotonic stack a little bit, and write a new solution, the time complexity is O(2n)==O(n).

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

 

标签:int,res,Daily,stk,length,Temperatures,739,new,temperatures
来源: https://www.cnblogs.com/feiflytech/p/15861491.html