Tuesday, January 8, 2019

739. Daily Temperatures


Version #1 Stack
二刷
73.18 %
class Solution {
    public int[] dailyTemperatures(int[] T) {
        // keep a decreasing sequence in stack
        // while we are seeing higher temperature than the top of the stack
        // we can pop and set the result
        int[] result = new int[T.length];
        // stack of indexes
        Stack<Integer> stack = new Stack<>();
        for (int i = 0; i < T.length; i++) {
            while (!stack.isEmpty() && T[i] > T[stack.peek()]) {
                int prev = stack.pop();
                result[prev] = i - prev;
            }
            stack.push(i);
        }
        return result;
    }
}

一刷
Actually the last while loop can be deleted, since the default value for array is already 0


class Solution {
    public int[] dailyTemperatures(int[] temperatures) {
int[] result = new int[temperatures.length];
// stack of indexes
Stack<Integer> stack = new Stack<>();
for (int i = 0; i < temperatures.length; i++) {
while (!stack.isEmpty() && temperatures[i] > temperatures[stack.peek()]) {
int prev = stack.pop();
result[prev] = i - prev;
}
stack.push(i);
}
while (!stack.isEmpty()) {
int prev = stack.pop();
result[prev] = 0;
}
return result;
}
}

No comments:

Post a Comment