프로그래머스 튜플 (C++)

2021. 4. 12. 19:07


문제 링크 : programmers.co.kr/learn/courses/30/lessons/64065

 

코딩테스트 연습 - 튜플

"{{2},{2,1},{2,1,3},{2,1,3,4}}" [2, 1, 3, 4] "{{1,2,3},{2,1},{1,2,4,3},{2}}" [2, 1, 3, 4] "{{4,2,3},{3},{2,3,4,1},{2,3}}" [3, 2, 4, 1]

programmers.co.kr

문제 풀이는 다음과 같다.

1. int형 key와 int형 value로 이루어진 맵을 만든다.

2. 튜플에 담겨진 숫자들을 key에 넣고, value의 값을 하나씩 증가시킨다.

이렇게되면 아래와 같은 로직이 구현된다.

(1) 가장 큰 value의 값 = 가장 많이 누적된 값이 튜플의 맨 앞에 오는 원소

(2) 가장 적은 value의 값 = 가장 적게 누적된 값이 튜플의 맨 끝에 오는 원소

3. map을 pair<int,int>형 벡터에 복사시킨다. 

4. 벡터의 second값, 즉, 누적 횟수가 가장 큰 수가 먼저 오도록 정렬한다.

5. 벡터의 first값을 정답 벡터에 추가해준다.

 

#include <string>
#include <vector>
#include <unordered_map>
#include <algorithm>

using namespace std;

bool comp(const pair<int,int> &a, const pair<int,int> &b){
    return a.second>b.second;
}

vector<int> solution(string s) {
    vector<int> answer;
    unordered_map<int,int> map;
    int temp = 0;
    string st = "";
    for(int i=0; i<s.size(); i++){
        if(s[i]==','){
            temp = stoi(st);
            map[temp]++;
            st = "";
        }
        else if(s[i]>='0'&&s[i]<='9') st+=s[i];
        else continue;
    }
    if(st!=""){
            temp = stoi(st);
            map[temp]++;
    }
    vector<pair<int,int>> v(map.begin(),map.end());
    sort(v.begin(),v.end(),comp);
    for(int i=0; i<v.size(); i++) answer.push_back(v[i].first);
    return answer;
}