Easy Java Solution using Stack


  • 1
    J

    Same idea with stack solution of largest rectangle in histogram:

    class Solution {
        public int[] dailyTemperatures(int[] temperatures) {
            
            if(temperatures == null || temperatures.length == 0) return new int[0];
            Stack<Integer> stack = new Stack<Integer>();
            int[] res = new int[temperatures.length];
            for(int i = 0; i <= temperatures.length - 1; i ++) {
                if(stack.isEmpty()) {
                    stack.push(i);
                    continue;
                } 
                while(!stack.isEmpty() && temperatures[i] > temperatures[stack.peek()]) {
                    int pre = stack.pop();
                    res[pre] = i - pre;
                }
                stack.push(i);
            }
            while(!stack.isEmpty()) {
                res[stack.pop()] = 0;
            }
            return res;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.