Daily Temperature

Given a list of daily temperatures T, return a list such that, for each day in the input, tells you how many days you would have to wait until a warmer temperature. If there is no future day for which this is possible, put 0 instead.

For example, given the list of temperatures T = [73, 74, 75, 71, 69, 72, 76, 73], your output should be [1, 1, 4, 2, 1, 1, 0, 0].

Note: The length of temperatures will be in the range [1, 30000]. Each temperature will be an integer in the range [30, 100].

์ž๋ฃŒ๊ตฌ์กฐ : Stack์ด์šฉ

์•Œ๊ณ ๋ฆฌ์ฆ˜ ์Šคํƒ ํ™œ์šฉํ•˜๊ธฐ ํ…Œํฌ๋‹‰๐ŸŒŸ 2-1. ์ผ๋‹จ ์ธ๋ฑ์Šค๊ฐ’์„ ์Šคํƒ์— ๋‹ค ๋„ฃ๋Š”๋‹ค. ์ฒ˜์Œ์—๋Š” ์Šคํƒ์ด ๋น„์–ด์žˆ๊ณ , result[i] = 0. - stack.push(i), (i๋Š” T.length-1๋ถ€ํ„ฐ ๊ฐ์†Œํ•˜๋Š” ๋ฐ˜๋ณต๋ฌธ) 2-2. ์›์†Œ๊ฐ’์„ ๋น„๊ตํ•œ๋‹ค. 2-3. ํŒ๋‹จ๊ธฐ์ค€์— ๋ถ€ํ•ฉํ•œ๋‹ค๋ฉด stack.peek()-i๋ฅผ ๊ฒฐ๊ณผ๊ฐ’์— ๋„ฃ๋Š”๋‹ค. 2-4. ๋ถ€ํ•ฉํ•˜์ง€ ์•Š๋Š”๋‹ค๋ฉด ๊ธฐ์ค€์— ๋ถ€ํ•ฉํ•˜๋Š” ๊ฒƒ์„ ์ฐพ์„ ๋•Œ๊นŒ์ง€ stack.pop()ํ•œ๋‹ค. stack์ด ๋นŒ ๋•Œ๊นŒ์ง€ ๋ชป์ฐพ์œผ๋ฉด ๊ฒฐ๊ณผ๊ฐ’์€ 0. => stack.isEmpty() ? 0 : stack.peek()-i =>2-1๊ณผ 2-4์—์„œ ๊ณตํ†ต๋œ ๋ถ€๋ถ„ : ์Šคํƒ์ด ๋น„์–ด์žˆ์œผ๋ฉด result[i] = 0

์•Œ๊ณ ๋ฆฌ์ฆ˜์„ Java๋กœ ๊ตฌํ˜„

class Solution {
    public int[] dailyTemperatures(int[] T) {
        int[] result = new int[T.length];
        Stack<Integer> stack = new Stack();
        for (int i = T.length - 1; i >= 0; --i) {
            while (!stack.isEmpty() && T[i] >= T[stack.peek()]) stack.pop();
            result[i] = stack.isEmpty() ? 0 : stack.peek() - i;
            stack.push(i);
        }
        return result;
    }
}

Last updated