Java Solution - Stack


  • 0
    E
    class Solution {
        public int[] dailyTemperatures(int[] temperatures) {
            int len = temperatures.length;
            int[] res = new int[len];
            if (len < 2) {
                return new int[len];
            }
            Stack<Integer> stack = new Stack<>();
            stack.push(0);
            for (int i = 1; i < temperatures.length; i++) {
                while (!stack.isEmpty() && temperatures[i] > temperatures[stack.peek()]) {
                    int prevIndex = stack.pop();
                    int duration = i - prevIndex;
                    res[prevIndex] = duration;
                }
                stack.push(i);
            }
            return res;
        }
    }
    

Log in to reply
 

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