문제
내가 작성한 정답
import java.util.Stack;
class Solution {
public int[] solution(int[] arr) {
Stack<Integer> stk = new Stack<>();
int i=0;
while (i<arr.length){
if(stk.isEmpty()) {
stk.add(arr[i]);
i++;
} else {
if(stk.peek()<arr[i]) {
stk.add(arr[i]);
i++;
} else stk.pop();
}
}
return stk.stream().mapToInt(a->a).toArray();
}
}
다른 사람들의 정답
import java.util.*;
class Solution {
public int[] solution(int[] arr) {
Stack<Integer> stack = new Stack();
for(int i : arr ){
if(stack.isEmpty()){
stack.push(i);
continue;
}
while(!stack.isEmpty() && i <= stack.peek()) {
stack.pop();
}
stack.push(i);
}
int[] answer = new int[stack.size()];
for(int i=0; i<answer.length; i++) {
answer[answer.length - 1 - i] = stack.pop();
}
return answer;
}
}
Share article