관리 메뉴

여름 언덕에서 배운 것

[0단계/2점]배열 만들기 6 본문

가랑비에 옷 젖는 줄 모른다 💻/🌰코테문풀_꾸준히

[0단계/2점]배열 만들기 6

잔뜩 2025. 2. 4. 00:20

다른 사람 풀이 중에 stack LIFO(Last-In-First-Out) 구조 를 이용해서 푼게 있었다.

stack.peek()는 스택의 맨 위(마지막)에 있는 요소를 가져온다.

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();
    }
}

 

내 풀이

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