문제
내가 작성한 정답
import java.util.*;
class Solution {
public int[] solution(int[] arr) {
ArrayList<Integer> answer = new ArrayList<>();
for(int i=0; i<arr.length; i++){
if(answer.isEmpty()) {
answer.add(arr[i]);
} else {
if(answer.get(answer.size()-1)==arr[i]) answer.remove(answer.size()-1);
else answer.add(arr[i]);
}
}
return answer.isEmpty()?new int[]{-1}:answer.stream().mapToInt(i->i).toArray();
}
}
다른 사람들의 정답
stack
: 나중에 들어온게 나감 ↔ queue : 처음에 들어온게 나감
→
제일 위 원소 확인하기 (peek()):
pop()은 꺼내면서 제거까지 하지만,peek()은 제일 위에 있는 원소가 뭔지 확인만 하고 스택에서 제거하지는 않는다
import java.util.Stack;
class Solution {
public int[] solution(int[] arr) {
Stack<Integer> stack = new Stack<>();
for (int no : arr) {
if (!stack.isEmpty() && no == stack.peek()) {
stack.pop();
} else {
stack.push(no);
}
}
return stack.isEmpty() ? new int[] { -1 } : stack.stream().mapToInt(i -> i).toArray();
}
}
Share article