Stack/Queue_같은숫자는 싫어 (C++)

선풍기·2023년 12월 24일

프로그래머스

목록 보기
2/8

문제

자료구조 부분의 Stack/Queue 부분의 같은숫자는 싫어 문제이다.

이런 문제이고

단순하게 unique함수를 이용해 단순하게 풀어도 되겠지만 자료구조를 활용해 풀어보고 싶어 Stack을 이용해 풀어보기로 했다.

정답

#include<iostream>
#include<stack>
#include <vector>
#include <algorithm>
using namespace std;
vector<int> solution(vector<int> arr)
{
    vector<int> answer;
    stack<int> st;
    reverse(arr.begin(), arr.end());
    for (int i = 0; i < arr.size(); i++) {
        st.push(arr[i]);
    }
    while (!st.empty()) {
        if (!answer.empty() && answer.back() == st.top()) {
            st.pop();
            continue;
        }
        else {
            answer.push_back(st.top());
            st.pop();
        }
    }
    return answer;
}

이런식으로 스택은 거꾸로 들어가기때문에 리버스를 이용해 뒤집어주고 넣었고,
순서대로 넣고 비교한 후 같은 숫자일 경우 pop만 해주었다.

답을 넣고 돌려보니 무난하게 정답이 나왔다.
레벨1이라 그런지 쉬운 문제였다.

0개의 댓글