같은 숫자는 싫어요

seheeee_97·2023년 11월 25일
0

회고팀

목록 보기
20/41
post-thumbnail



import java.util.*;

public class Solution {
    public int[] solution(int []arr) {
        Stack<Integer> stack = new Stack<>();
        
        for(int i=0; i<arr.length; i++) {
            if(!stack.isEmpty() && stack.peek() == arr[i]) {	//스택이 비어있지 않고 스택 top 값이 배열과 같으면
                stack.pop();	//기존에 있던 숫자를 빼고
            }
            stack.push(arr[i]);		//현재 배열의 숫자를 넣는다
        }
        
        //스택의 값을 pop해서 배열에 역순으로 저장
        int[] answer = new int[stack.size()];
        for (int i = stack.size()-1; i >= 0; i--) {
            answer[i] = stack.pop();
        }
        
        return answer;
    }
}

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

0개의 댓글