💡풀이
- Stack 사용
import java.util.*;
public class Solution {
public int[] solution(int []arr) {
Stack<Integer> stack = new Stack<>();
for(int n : arr){
if(stack.isEmpty() || stack.peek() != n){
stack.push(n);
}
}
return stack.stream().mapToInt(Integer::intValue).toArray();
}
}
💡풀이 2
- Stack을 ArrayDeque로 구현
import java.util.*;
import java.util.stream.Collectors;
public class Solution {
public int[] solution(int []arr) {
Deque<Integer> stack = new ArrayDeque<>();
for (int num : arr) {
if (stack.isEmpty() || stack.peek() != num) {
stack.push(num);
}
}
List<Integer> list = stack.stream().collect(Collectors.toList());
Collections.reverse(list);
return list.stream().mapToInt(Integer::intValue).toArray();
}
}
📖새로 배운 부분
💡왜 Stack이 아니라 ArrayDeque로 Stack을 구현했나요?
[Java, Stack] 왜 Stack이 아닌 Deque로 스택을 구현해야 할까?
Stack 클래스가 상속하고 있는 Vector가 문제가 되기 때문에 Deque 클래스 사용을 권장한다.⚠️Stack stack = new Stack(); Vector는 자바 버전 1부터 있었던 굉장히 오래된 클래스이기 때문에 여러모로 취약
devoks.tistory.com
GitHub - okjunghyeon/Programmers_CodingTest: 프로그래머스 관련 코딩테스트 문제를 풀이한 저장소입니다.
프로그래머스 관련 코딩테스트 문제를 풀이한 저장소입니다. Contribute to okjunghyeon/Programmers_CodingTest development by creating an account on GitHub.
github.com
'CodingTest > Programmers' 카테고리의 다른 글
[프로그래머스, Java] 최대공약수와 최소공배수 (0) | 2025.07.10 |
---|---|
[Java] 유클리드 호제법이란? (0) | 2025.07.10 |
[프로그래머스, Java] 직사각형 별찍기 (0) | 2025.07.10 |
[프로그래머스, Java] 행렬의 덧셈 (0) | 2025.07.10 |
[프로그래머스, Java] 문자열 다루기 기본 (0) | 2025.07.09 |