내 답안
import java.util.ArrayList;
class Solution {
public int[] solution(int[] arr) {
ArrayList<Integer> tmp= new ArrayList();
int i=0;
while(i<arr.length){
if(tmp.size()==0){
tmp.add(arr[i]);
i=i+1;
}else{
int last=tmp.get(tmp.size()-1);
if(tmp.size()!=0 && last<arr[i]){
tmp.add(arr[i]);
i=i+1;
}
else if(tmp.size()!=0 && last>=arr[i]){
tmp.remove(tmp.size()-1);
}
}
}
int stk[]=new int[tmp.size()];
for(int k=0;k<tmp.size();k++){
stk[k]=tmp.get(k).intValue();
}
return stk;
}
}
Java
복사
다른 사람 풀이법
import java.util.*;
class Solution {
public Stack<Integer> solution(int[] arr) {
Stack<Integer> stack = new Stack<>();
int i = 0;
while (i < arr.length) {
if (stack.empty() || stack.peek() < arr[i]) {
stack.push(arr[i]);
i++;
} else if (stack.peek() >= arr[i]) {
stack.pop();
}
}
return stack;
}
}
Java
복사
import java.util.Stack;
class Solution {
public int[] solution(int[] arr) {
Stack<Integer> stack = new Stack<>();
for (int num : arr) {
while (!stack.isEmpty() && num <= stack.peek())
stack.pop();
stack.push(num);
}
return stack.stream().mapToInt(i -> i).toArray();
}
}
Java
복사