본문 바로가기

Coding Test/프로그래머스

[프로그래머스/자바] 같은 숫자는 싫어

import java.util.Stack;

public class Solution {
    public int[] solution(int[] arr) {
        if (arr.length == 1) return arr;

        Stack<Integer> stack = new Stack<>();
        stack.push(arr[0]);

        for (int i = 1; i < arr.length; i++) {
            if (stack.peek() == arr[i]) {
                stack.pop();
            }
            stack.push(arr[i]);
        }

        int[] answer = new int[stack.size()];

        for (int i = stack.size() - 1; i >= 0; i--) {
            answer[i] = stack.pop();
        }

        return answer;
    }
}