코딩테스트 준비/기타문제
[JAVA][Array] Daily Temperature
AtoZ 개발자
2021. 1. 26. 14:00
반응형
1. 문제
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].
2. 문제해설
일일 온도 목록 T 배열이 주어졌을때 T 배열에 있는 특정 인덱스에서 얼마나 지나야 기온이 높아 지는지를 계산하여 결과값에 반영해준다. 만약 온도가 더 높아지는 날이 없으면 0을 반환한다.
3. 코드포맷
import java.util.Stack;
public class DailyTemperature {
public static void main(String[] args) {
int[] nums = {73, 74, 75, 71, 69, 72, 76, 73};
int[] res = dailyTemperatures(nums);
System.out.println("====result===");
for(int i : res) {
System.out.print(i+" ");
}
}
}
4. 접근 방법
특정날을 기준으로 향후의 온도를 매번 비교한다. 비교하여 현재보다 온도가 높다면 인덱스의 차를 구한다.
ex) T = [73, 74, 72, 75] 한다면 T[0]=73도는 T[1]=74도 낮기때문에 Result[0]=1이 입력된다.
더 나아가 T[1]=74는 T[2]=72보다 높기 때문에 다음 인덱스로 넘어가서 T[3]=75를 확인한다. T[3]보다 낮기때문에 Result[1]=2이다.
5. 코드
import java.util.Stack;
public class DailyTemperature {
public static void main(String[] args) {
int[] nums = {73, 74, 75, 71, 69, 72, 76, 73};
int[] res = dailyTemperatures(nums);
System.out.println("====result===");
for(int i : res) {
System.out.print(i+" ");
}
}
private static int[] dailyTemperatures(int[] nums) {
//결과를 담을 그릇
int[] result = new int[nums.length];
//온도를 담을 그릇
Stack<Integer> stack = new Stack<Integer>();
for(int i=0;i<nums.length;i++) {
//만약 스택이 비어있지 않고, 현재 stack에 peek값 번째의 nums와 nums[i]를 비교
while(!stack.isEmpty()&&nums[stack.peek()]<=nums[i]) {
int index = stack.pop();
result[index]=i-index;
}
stack.push(i);
}
return result;
}
}
반응형