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

☑️ 문제

프로그래머스 12906

☑️ 풀이

처음 푼 풀이

  • Stack과 List를 활용하여 풀었다.
    • Stack에서 답을 순차적으로 꺼내기 위해 List를 사용하였다.
    • 자료구조를 두 개 사용해서인지 실행 시간이 상당히 오래 걸렸다.
//시간: 3.20ms
//메모리: 79.6MB

import java.util.*;

public class Solution {
    public int[] solution(int[] arr) {
        List<Integer> list = new ArrayList<>();
        Stack<Integer> stack = new Stack<>();
        for (int num : arr) {
            if (stack.isEmpty()) {
                stack.push(num);
            } else {
                int stackNum = stack.peek();
                if (stackNum != num) {
                    list.add(stack.pop());
                    stack.push(num);
                }
            }
        }

        if (stack.size() == 1) {
            list.add(stack.pop());
        }

        return list.stream().mapToInt(Integer::intValue).toArray();
    }
}

두 번째 풀이

  • Stack만 사용하여 풀었더니 실행 시간이 훨씬 더 줄어든 걸 볼 수 있었다.
  • Stack에서 마지막 요소부터 pop() 해서 answer 배열에 집어넣는 형식으로 답을 출력하였다.
//시간: 0.33ms
//메모리: 74.2MB

import java.util.*;

public class Solution {
    public int[] solution(int[] arr) {
        Stack<Integer> stack = new Stack<>();
        for (int num : arr) {
            if (stack.isEmpty()) {
                stack.push(num);
            } else {
                if (stack.peek() != num) {
                    stack.push(num);
                }
            }
        }

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

        return answer;
    }
}

© 2021. All rights reserved.

yaejinkong의 블로그