준비/알고리즘 공부
[스택/큐] daily tempuratures
chuseok
2025. 5. 19. 10:46
int[] temperatures가 주어질 때, 현재 기온보다 더 따뜻해질 때까지 걸리는 일수 날짜별로 구하기
풀이 순서
for()
stack 사용
while(!stack.isEmtpy() && temperatures[peek()] < temperatures[i]) {
i - 스택에 누적한 index
}
push()
풀이 시작 11:27
풀이 종료 22:30
다시 풀이
풀이 참고함
내 풀이
class Solution {
public int[] dailyTemperatures(int[] temperatures) {
Deque<Integer> stack = new ArrayDeque<>();
for(int i=0; i<temperatures.length; i++) {
int idx = 0;
while(!stack.isEmpty() && temperatures[stack.peek()] < temperatures[i]) {
idx = i-stack.remove();
}
stack.push(idx);
}
}
}
int[]로 반환해야 하는데 어떻게 하지?
근데 stack에 idx 차를 넣는게 맞나?
그럼 2번째 차례가 왔을 때 stack이 빈 상태에서 새로 push 되고 3번째 차례가 값이 크면 i(2번째 idx)-0(3번째 idx?)인데
0을 빼면 차이를 뺀게 아니잖아
다른 사람의 풀이 참고
class Solution {
public int[] dailyTemperatures(int[] temperatures) {
Deque<Integer> stack = new ArrayDeque<>();
int[] answer = new int[temperatures.length];
for(int i=0; i<temperatures.length; i++) {
while(!stack.isEmpty() && temperatures[stack.peek()] < temperatures[i]) {
int idx = stack.remove();
answer[idx] = i-idx;
}
stack.push(i);
}
return answer;
}
}