알고리즘/프로그래머스
[프로그래머스] 튜플 문제풀이 c++
_hoji
2022. 4. 14. 16:29
주어진 문제에서 튜플의 원소는 중복이 없다.
따라서 특정 튜플을 표현하는 집합이 주어졌을때,
모든 숫자에 대해 몇 번 사용되었는지 확인하면
가장 많이 사용된 숫자가 튜플의 시작이고 가장 적게 사용된 숫자가 튜플의 끝이다.
따라서 문자열을 탐색하면서 숫자는 map<int,int>자료구조에 넣고(map의 first는 숫자, second는 개수)
이후 map을 전체 탐색하여 pair<int, int>를 갖는 vector에 값을 넣는다.
vector list를 pair.second(개수)의 내림차순으로 sort하면
pair.first를 확인하여 튜플을 구할 수 있다.
#include <string>
#include <vector>
#include <map>
#include <algorithm>
using namespace std;
bool cmp(pair<int,int> p1, pair<int,int> p2){
if(p1.second > p2.second){
return true;
}
else
return false;
}
vector<int> solution(string s) {
vector<int> answer;
string x ="";
map<int,int> m;
for(int i=0; i<s.size(); i++){
if(isdigit(s[i])){
x += s[i];
}
else{
if(x!= ""){
m[stoi(x)] ++;
x= "";
}
}
}
vector<pair<int,int>> list;
for(auto it=m.begin(); it != m.end(); it++){
list.push_back(make_pair(it->first,it->second));
}
sort(list.begin(), list.end(), cmp);
for(int i=0; i<list.size(); i++)
answer.push_back(list[i].first);
return answer;
}