[프로그래머스/C++]Lv.2 - 튜플

YH J·2023년 9월 21일
0

프로그래머스

목록 보기
151/168

문제 링크

https://school.programmers.co.kr/learn/courses/30/lessons/64065

내 풀이

처음엔 문제를 잘못보고 stringstream을 써서 숫자만 뽑아서 대충했다가 다시했다.
문자열을 파싱해서 숫자를 뽑아서 vec에 넣고 닫는 괄호'}'가 나오면 만든 vec를 vecs에 넣어준다.
나온 vecs를 vec의 크기를 기준으로 오름차순하면 가장 작은 집합부터 나열된다.
가장 작은 크기의 집합부터 원소가 이미 나왔는지 체크해가면서 answer에 차례대로 추가해나간다.

내 코드

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

using namespace std;

bool cmp(vector<int> a, vector<int> b)
{
    return a.size() < b.size();
}

vector<int> solution(string s) {
    vector<int> answer;
    
    bool Check[100001] = {false, };
    bool open = false;
    
    vector<vector<int>> vecs;
    vector<int> vec;
    string num;
    
    for(int i = 1; i < s.size() - 1; i++)
    {
        if(s[i] == '{')
            open = true;
        else if(open == true && (s[i] >= '0' && s[i] <= '9'))
            num += s[i];
        else if(open == true && s[i] == ',')
        {
            vec.push_back(stoi(num));
            num = "";
        }
        else if(open == true && s[i] == '}')
        {
            vec.push_back(stoi(num));
            num = "";
            open = false;
            vecs.push_back(vec);
            vec.clear();
        }
    }
    
    sort(vecs.begin(), vecs.end(), cmp);
    
    for(int i = 0; i < vecs.size(); i++)
    {
        for(int j = 0; j < vecs[i].size(); j++)
        {
            if(!Check[vecs[i][j]])
            {
                Check[vecs[i][j]] = true;
                answer.push_back(vecs[i][j]);
            }
        }
    }
    
    return answer;
}

다른 사람의 풀이

#include <bits/stdc++.h>
using namespace std;

vector<int> solution(string s) {
    int st[101010]={};
    vector<int> answer;
    string tmp;
    for(char i: s){
        if(i-'0' >=0 && i-'0' <=9){
            tmp += i;
        }
        else{
            if(tmp.length())
                st[stoi(tmp)]++, tmp.clear();
        }
    }
    vector<pair<int, int>> v;
    for(int i =0; i <101010; i++)
        if(st[i])
            v.push_back({st[i], i});
    sort(v.begin(), v.end());
    reverse(v.begin(),v.end());
    for(auto it: v) answer.push_back(it.second);
    return answer;
}

다른 사람의 풀이 해석

배열에서 가장 앞에있는 원소가 모든 튜플에서 가장 많이 나오는 수 이므로
파싱하면서 모든 숫자가 나온 횟수를 기록해서 검출해낸다.
횟수를 내림차순으로 정렬하면 그게 원하는 답이다.
훨씬 쉽고 빠른방법이다.

profile
게임 개발자 지망생

0개의 댓글