https://leetcode.com/problems/daily-temperatures/description/

 

Daily Temperatures - LeetCode

Can you solve this real interview question? Daily Temperatures - Given an array of integers temperatures represents the daily temperatures, return an array answer such that answer[i] is the number of days you have to wait after the ith day to get a warmer

leetcode.com

 

주어진 온도 배열에서 현재의 온도보다 값이 늘어나기 까지 걸리는 일 수를 구하는 문제이다.
인덱스를 늘리며 스택에 온도가 낮은 경우를 저장해 가며 해결하면 효율적으로 해결할 수 있다.

 

온도가 올라간 날짜(인덱스)의 경우 스택에서 차례대로 제거되기 때문에 스택에서 제거 가능할 때까지 반복하고, 신규 값을 스택에 넣어주면 된다. int[] 타입을 써도 되지만 가독성과 편의성을 위해 인덱스를 저장하는 별도의 클래스를 만들었다.

완성 코드는 아래와 같다.

import java.util.*;  
  
public class Solution {  
    public int[] dailyTemperatures(int[] temperatures) {  
  
        int[] answer = new int[temperatures.length];  
        Deque<IdxTemp> stack = new ArrayDeque<>();  
  
        for(int i = 0; i < temperatures.length; i++){  
            int curTemp = temperatures[i];  
  
            // 현재보다 낮은 온도의 이전의 값들을 제거하며 답에 저장  
            while(!stack.isEmpty() && stack.peekLast().temp < curTemp){  
                IdxTemp lowTemp = stack.pollLast();  
                answer[lowTemp.idx] = i - lowTemp.idx;  
            }  
  
            stack.addLast(new IdxTemp(i, curTemp));  
        }  
        return answer;  
    }  
  
    private static class IdxTemp{  
        int idx;  
        int temp;  
  
        IdxTemp(int idx, int temp){  
            this.idx = idx;  
            this.temp = temp;  
        }  
    }  
}

'Algolithm-Leetcode > Stacks' 카테고리의 다른 글

Largest Rectangle in Histogram  (1) 2026.08.24
Generate Parentheses  (0) 2026.08.21
Min Stack  (0) 2026.08.08
Valid Parentheses  (1) 2026.07.22

+ Recent posts