문제
내가 작성한 정답
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();
}
}다른 사람들의 정답
import java.util.Stack;
class Solution {
public int[] solution(int[] arr) {
Stack<Integer> stack = new Stack<>(); // LIFO(Last In First Out) 구조의 스택 생성
for (int no : arr) {
// 스택이 비어있지 않고, 현재 값이 스택의 최상단(마지막 저장 값)과 같다면
if (!stack.isEmpty() && no == stack.peek()) {
stack.pop(); // 최상단 값을 제거 (같은 값이 겹치면 제거)
} else {
stack.push(no); // 다르면 스택에 값을 추가 (쌓기)
}
}
// 스택이 비어있으면 [-1] 리턴, 아니면 스택 요소를 배열로 변환하여 리턴
return stack.isEmpty() ? new int[] { -1 } : stack.stream().mapToInt(i -> i).toArray();
}
}
개념 | 설명 |
스택(Stack) | 데이터를 한 쪽 끝에서만 넣거나(push), 꺼낼 수 있는 자료구조 |
동작 원리 | 후입선출(LIFO, Last In First Out) - 가장 나중에 들어간 데이터가 가장 먼저 나옴 |
제공 클래스 | Java에서 java.util.Stack<E>클래스로 기본 제공 |
push(E item) | 스택의 최상단에 요소를 추가 |
pop() | 스택 최상단 요소를 꺼내고 제거 |
peek() | 스택 최상단 요소를 제거지 않고 확인만 함 |
isEmpty() | 스택이 비어있는지 여부 반환 |
Share article