본문 바로가기
Algorithm/Programmers

[Programmers] Lv.0 / 배열 만들기 6 / Java

by unknownomad 2024. 2. 6.

문제

 

풀이

  • 날것 버전
import java.util.*;

class Solution {
    public int[] solution(int[] arr) {
        
        List<Integer> result = new ArrayList<>();
        
        for(int i = 0; i < arr.length; i++) {
            if(result.isEmpty() || i == 0 || arr[i] != result.get(result.size() - 1)) {
                result.add(arr[i]);
            } else if(arr[i] == result.get(result.size() - 1)) {
                result.remove(result.size() - 1);
            }
        }
        return result.isEmpty() ? new int[] {-1} : result.stream().mapToInt(Integer::intValue).toArray();
    }
}
  • 정리 버전
import java.util.*;

class Solution {
    public int[] solution(int[] arr) {
    
        List<Integer> result = new ArrayList<>();
        
        for (int num : arr) {
            if (result.isEmpty() || num != result.get(result.size() - 1)) {
                result.add(num);
            } else {
                result.remove(result.size() - 1);
            }
        }
        return result.isEmpty() ? new int[] {-1} : result.stream().mapToInt(Integer::intValue).toArray();
    }
}
  • 다른 풀이
import java.util.Stack;

class Solution {
    public int[] solution(int[] arr) {

        Stack<Integer> stack = new Stack<>();
        
        for(int num : arr) {
            if(!stack.isEmpty() && num == stack.peek()) {
                stack.pop();
            } else {
                stack.push(num);
            }
        }
        return stack.isEmpty() ? new int[] {-1} : stack.stream().mapToInt(i -> i).toArray();
    }
}

 

출처

https://school.programmers.co.kr/learn/courses/30/lessons/181859

댓글