hyunjin

[level 1] 같은 숫자는 싫어, iterator 선언 , unique 사용 본문

알고리즘 연습/프로그래머스

[level 1] 같은 숫자는 싫어, iterator 선언 , unique 사용

_h.j 2020. 7. 13. 21:20
728x90

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

 

첫 번째 풀이 (답은 맞았으나 효율성 테스트 통과 못함)

#include <vector>
#include <iostream>

using namespace std;

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

    answer.assign(arr.begin(), arr.end());

    for(vector<int>::iterator elem = answer.begin();;){
        if( (elem+1) == answer.end() ) break;
      
        if( *elem == *(elem+1)) {
            answer.erase(elem+1);
        }
        else{ elem++;}
    }

    return answer;
}

 

두 번째 풀이 (실패)

#include <vector>

using namespace std;

vector<int> solution(vector<int> arr) 
{
    vector<int> answer(arr.size());
    answer.assign(arr.begin(),arr.end());
    vector<int>::iterator it = answer.begin();

    while( (it+1) != answer.end() ){    
        if( *it == *(it+1) ){
            answer.erase(it+1 );  // 여기서 core dump 오류 난다. 
        }
        it++;
    }
    return answer;
}

왜 저 부분에서 오류가 나는지 잘 모르겠다. 

 

세 번째 풀이

#include <vector>

using namespace std;

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

    return answer;
}

성공

 

다른 사람 풀이( unique 사용 )

#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;
}
#include <vector>
#include <algorithm>

using namespace std;

vector<int> solution(vector<int> arr) 
{
    vector<int> answer(arr.size());
    answer.assign(arr.begin(),arr.end());
    answer.erase(unique(answer.begin() , answer.end()),answer.end());    
    return answer;
}

 

배운 내용

  • unique
    • 중복된 원소를 제거하며  앞에서부터 원소를 채워 나간다. 
    • 헤더 파일 : include <algorithm>
    • n개 원소에 대한 시간 복잡도는 O(n)

 

 

참고

iterator 선언 : https://m.blog.naver.com/PostView.nhn?blogId=kks227&logNo=60208809639&proxyReferer=https:%2F%2Fwww.google.com%2F

unique : http://blog.naver.com/PostView.nhn?blogId=withham1&logNo=221102099316&parentCategoryNo=&categoryNo=16&viewDate=&isShowPopularPosts=false&from=postView

728x90