본문 바로가기
알고리즘/[프로그래머스] JAVA

[코딩 기초 트레이닝] 배열 만들기6

by 코딩맛집 2024. 2. 4.

문제 :

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

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

 

해결 :

import java.util.*;

class Solution {
    public int[] solution(int[] arr) {
        List<Integer> stk = new ArrayList<>();
        int i = 0;
        while(i< arr.length){
            if(stk.size() == 0){
                stk.add(arr[i]);
                i++;
            }else if(stk.get(stk.size()-1) == arr[i]){
                stk.remove(stk.size()-1);
                i++;
            }else if(stk.get(stk.size()-1) != arr[i]){
                stk.add(arr[i]);
                i++;
            }
            
        }


        if(stk.isEmpty()){
            return new int[]{-1};
        }
        
        return stk.stream().mapToInt(Integer::intValue).toArray();
    }
}

 

다른 사람 풀이 :

import java.util.Stack;

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

        Stack<Integer> stack = new Stack<>();

        for (int no : arr) {
            if (!stack.isEmpty() && no == stack.peek()) {
                stack.pop();
            } else {
                stack.push(no);
            }
        }

        return stack.isEmpty() ? new int[] { -1 } : stack.stream().mapToInt(i -> i).toArray();
    }
}