-
LIFO - java알고리즘 2023. 12. 2. 18:23
문제: 매일의 온도를 나타내는 int형 배열 temperatures가 주어진다. answer배열의 원소 answer[i]는 i번째 날의 온도보다 더 따뜻해지기까지 며칠을 기다려야하는지 나타낸다. 만약 더 따뜻해지는 날이 없다면 answer[i] == 0이다.
answer 배열을 반환하는 함수를 구현하시오.
제약조건
1<=temparatures.length <= 10^5
30 <= temparatures[i] <= 100
import java.util.Arrays; import java.util.Stack; public class LIFO { public static int[] dailyTemperatures(int[] temperatures) { int[] ans = new int[temperatures.length]; Stack<Integer[]> stack = new Stack<>(); for(int i=0; i<temperatures.length; i++) { Integer[] day = {temperatures[i],i}; while(stack.size()!= 0 && stack.peek()[0] < temperatures[i]) { ans[stack.peek()[1]] = i-stack.peek()[1]; stack.pop(); } stack.push(day); } return ans; } public static void main(String[] args){ int[] tem1 = {73, 74, 75, 71, 69, 72, 76, 73}; System.out.println(Arrays.toString(dailyTemperatures(tem1))); } }
'알고리즘' 카테고리의 다른 글
재귀 (1) 2023.12.03 Dictionary - 가장 긴 연속된 수열 (4) 2023.12.03 딕셔너리 (2) 2023.12.03 스택(stack) (0) 2023.12.02 Two Pointer (2) 2023.12.02