class Solution {
public int[] solution(int[] arr) {
int[] stk = {};
return stk;
}
}
해결법
방법 1
import java.util.*;
class Solution {
public int[] solution(int[] arr) {
List<Integer> stk = new ArrayList<>();
for (int i = 0; i < arr.length;) {
if (stk.size() == 0) {
stk.add(arr[i]);
i++;
} else if (stk.size() != 0 && stk.get(stk.size() - 1) < arr[i]) {
stk.add(arr[i]);
i++;
} else {
stk.remove(stk.size() - 1);
}
}
int[] answer = new int[stk.size()];
for (int i = 0; i < answer.length; i++) {
answer[i] = stk.get(i);
}
return answer;
}
}
방법 2
import java.util.*;
class Solution {
public int[] solution(int[] arr) {
Stack<Integer> stk = new Stack();
for (int i : arr) {
if (stk.isEmpty()) {
stk.push(i);
continue;
}
while (!stk.isEmpty() && i <= stk.peek()) {
stk.pop();
}
stk.push(i);
}
int[] answer = new int[stk.size()];
for (int i = 0; i < answer.length; i++) {
answer[answer.length - 1 - i] = stk.pop();
}
return answer;
}
}
배열 만들기 4 Lv. 0