[C++] 같은 숫자는 싫어 - vector의 unique()

wansuper·2023년 12월 28일
0

CodingTest

목록 보기
18/34

정답 코드 - 정답률 100%

#include <vector>
#include <iostream>
#include <algorithm>

using namespace std;

vector<int> solution(vector<int> arr) 
{
    vector<int> answer;
    
    vector<int>::iterator itr;
    
    // unique() 함수: 처음부터 끝까지 연속된 중복 원소를 맨 뒤의 쓰레기 값으로 빼주는 함수
    itr = unique(arr.begin(), arr.end());
    
    arr.erase(itr, arr.end());
    // arr.erase(unique(arr.begin(), arr.end()), arr.end());
    
    answer = arr;

    return answer;
}

또 다른 풀이 - 정답률 95.8%로 오답

#include <vector>
#include <iostream>
#include <algorithm>

using namespace std;

vector<int> solution(vector<int> arr) 
{
    vector<int> answer;
    
    for (int i = 0; i < arr.size(); i++) {
        if (arr[i] != arr[i+1]) {
            answer.push_back(arr[i]);
        }
    }

    return answer;
}

  • 두 풀이의 차이점은 중복된 원소를 맨 뒤의 쓰레기 값으로 빼주는 unique() 함수를 썼는지에 대한 유무다. 두번째 풀이는 조금만 생각해도 머릿속에서 충분히 나올 수 있을만한 풀이이다. 하지만 unique 함수를 안썼기 때문에 정확한 처리가 힘들다.

  • unique() 함수는 remove 함수처럼 실제로 원소를 그렇게 만들어 주는게 아니라 해당하는 원소를 쓰레기 값으로 뒤로 뺀다. 따라서, erase로 직접 해당 쓰레기 값을 지워야되며, unique() 함수의 사용을 위해 다음과 같이 algorithm 을 include 해야 한다.

#include <algorithm>
  • iterator를 굳이 사용하지 않고 주석 처리한 것처럼 한 줄에 써도 된다.
arr.erase(unique(arr.begin(), arr.end()), arr.end());

형태 기억하기!

profile
🚗 Autonomous Vehicle 🖥️ Study Alone

0개의 댓글