-
[프로그래머스] 같은 숫자는 싫어Coding Test 2023. 6. 4. 20:39728x90
Stack -> Fist In Last Out
import java.util.*; public class Solution { public int[] solution(int []arr) { Stack<Integer> st = new Stack<>(); st.push(arr[0]); // arr[0]을 초기값으로 설정 for(int i = 1; i < arr.length; i++) { if(st.peek() == arr[i]) { // 스택에 저장된 맨 위 요소와 arr 비교 continue; } else { st.push(arr[i]); // 스택에 저장 } } int[] answer = new int[st.size()]; // 스택 크기만큼 answer 크기 지정 for(int i = answer.length - 1; i >= 0; i--) { // FILO이기 때문에 마지막 요소부터 저장 answer[i] = st.pop(); } return answer; } }
728x90반응형'Coding Test' 카테고리의 다른 글
[프로그래머스] 완주하지 못한 선수 (0) 2023.06.08 [프로그래머스] 타겟 넘버 (0) 2023.06.06 [프로그래머스] 최소직사각형 (0) 2023.06.06 [프로그래머스] K번째 수 (0) 2023.06.04 [프로그래머스] 폰켓몬 (0) 2023.06.04