첫 풀이
import java.util.Stack;
class Solution {
public int[] solution(int[] numbers) {
int[] answer = new int[numbers.length];
Stack<Number> stack = new Stack<>();
for (int i = 0; i < numbers.length; i++) {
if (stack.isEmpty()) {
stack.push(new Number(numbers[i], i));
continue;
}
while (!stack.isEmpty() && numbers[i] > stack.peek().num) {
Number top = stack.pop();
answer[top.idx] = numbers[i];
}
stack.push(new Number(numbers[i], i));
}
while (!stack.isEmpty()) {
Number top = stack.pop();
answer[top.idx] = -1;
}
return answer;
}
}
class Number {
int num;
int idx;
public Number(int num, int idx) {
this.num = num;
this.idx = idx;
}
}
코드 리팩토링
import java.util.Arrays;
import java.util.Stack;
class Solution {
public int[] solution(int[] numbers) {
int[] answer = new int[numbers.length];
Arrays.fill(answer, -1);
Stack<Integer> stack = new Stack<>();
for (int arrIdx = 0; arrIdx < numbers.length; arrIdx++) {
while (!stack.isEmpty() && numbers[arrIdx] > numbers[stack.peek()]) {
int stkIdx = stack.pop();
answer[stkIdx] = numbers[arrIdx];
}
stack.push(arrIdx);
}
return answer;
}
}