본문 바로가기
프로그래밍/프로그래머스

C++ 같은 숫자는 싫어(프로그래머스)

by devsu 2020. 6. 1.

프로그래머스_같은 숫자는 싫어

https://programmers.co.kr/

 

배열

문제 해석

 

이 문제를 풀기위해 이해해야 할 내용은 다음과 같습니다.

 

목표

연속적인 숫자를 제거한 배열 만들기

방법

1. 연속으로 나온 숫자인지 확인

2. 연속이 아닌 경우 배열에 추가

 

결과

연속적인 숫자를 제거한 배열 만들기

 

1. 통과한 코드

#include <vector>
#include <iostream>

using namespace std;

vector<int> solution(vector<int> arr)
{
    vector<int> answer;
    for (int i = 0; i < arr.size(); i++)
    {
        int nVal = arr.at(i);
        if (answer.size() > 0)
        {
            int n = answer.back();
            if (nVal == n)
                continue;
            else
                answer.push_back(nVal);
        }
        else
        {
            answer.push_back(nVal);
        }
    }
    return answer;
}

너무 기본이라 금방 풀고 다른사람이 구현한 코드를 하나 봤는데..

 

2. 다른 사람의 코드

#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;

vector<int> solution(vector<int> arr) 
{

    arr.erase(unique(arr.begin(), arr.end()),arr.end());

    vector<int> answer = arr;
    return answer;
}

한줄로 처리를 하였다 ㄷㄷ...

 

C++ unique reference

int myints[] = {10,20,20,20,30,30,20,20,10};           // 10 20 20 20 30 30 20 20 10
  std::vector<int> myvector (myints,myints 9);

  // using default comparison:
  std::vector<int>::iterator it;
  it = std::unique (myvector.begin(), myvector.end());   // 10 20 30 20 10 ?  ?  ?  ?

unique를 사용하면 연속적인 값들을 뒤로 쓰레기값처럼 보내버린 후 쓰레기값 시작 위치를 반환한다.

그러니 erase를 써서 그때부터 end까지 지워버리면 끝!