Notice
Recent Posts
Recent Comments
Link
«   2026/05   »
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
31
Tags
more
Archives
Today
Total
관리 메뉴

yesolje

프로그래머스_고득점kit_스택큐_같은 숫자는 싫어 본문

코딩테스트

프로그래머스_고득점kit_스택큐_같은 숫자는 싫어

yesolje 2025. 3. 6. 11:33

풀이

import java.util.*;

public class Solution {
    public int[] solution(int []arr) {
        
        Stack<Integer> st = new Stack<>();
        for(int number : arr){
            if(st.empty()){
                st.push(number);
            }else if(st.peek() != number){
                st.push(number);
            }
        }
        
        int[] answer = new int[st.size()];
        
        for(int i = st.size() - 1; i >= 0; i--){
            answer[i] = st.pop();
        }
        
        return answer;
        
    }
}

개념정리

 

Stack

✔️ 상자에 물건을 쌓아 올리듯 데이터를 쌓는 자료 구조이다

✔️ 마지막에 저장한 데이터를 가장 먼저 꺼내는 LIFO(Last in first out) 구조를 가지고 있다

✔️ 수식 계산, undo/redo, 웹 브라우저의 뒤로 / 앞으로 구현에 이용한다

 

메서드

메서드 설명
boolean empty() Stack 이 비어있는지를 반환
Object peek() Stack 의 맨 위에 저장된 객체를 반환(꺼내지 않음)
Object pop() Stack 의 맨 위에 저장된 객체를 꺼냄
Object push(Object item) Stack 에 객체를 저장 
int search(Object o) Stack에서 주어진 객체(o)를 찾아서 그 위치를 반환
못찾을 경우 -1 을 반환
배열과 달리 위치는 0이 아닌 1부터 시작

 

Stack의 선언 및 사용

import java.util.*;

public class Solution {
    public void solution() {
        
        Stack<Integer> st = new Stack<>();
        
        st.push(1);
        st.push(2);
        st.push(3);
        
        while(st.isEmpty()){
        	System.out.println(st.pop()); 
        }
        
    }
}