본문 바로가기
C++ 코딩 문제 풀이/프로그래머스

[Programmers] 튜플

by 섬댕이 2023. 9. 25.

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

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

 


 

문제 해결 과정

착안

중복되는 원소가 없는 튜플에 대한 집합 표현만 주어지므로, 집합 내에서 중복하여 많이 등장하는 숫자일수록 튜플의 앞에 위치하는 원소임에 착안하여 문제를 해결하고자 하였다.

 

구현

이를 구현하기 위해, 원소 별로 집합 내에서의 등장 횟수를 카운트할 때 std::unordered_map<> 클래스를 활용한 다음, pair<> 형식의 원소들을 std::vector<> 클래스로 옮겨 등장 횟수에 대해 내림차순으로 정렬하여 문제를 해결하였다.

 

[스포 주의] 아래 '더보기'를 누르면 코드가 나오니 주의하세요~

더보기
#include <string>
#include <vector>
#include <unordered_map>
#include <algorithm>

using namespace std;

vector<int> solution(string s)
{
	unordered_map<string, int> Numbers;
	string elem;
	for (char c : s)
	{
		if (0 <= c - '0' && c - '0' <= 9)
			elem.push_back(c);

		if (c == ',' || c == '}')
		{
			if (elem == "")
				continue;
			
			Numbers[elem]++;
			elem = "";
		}
	}

	std::vector<std::pair<std::string, int>> sorted(Numbers.begin(), Numbers.end());
	sort(sorted.begin(), sorted.end(),
		 [](const pair<string, int>& a, const pair<string, int>& b)
		 {
			 return a.second > b.second;
		 });

	vector<int> answer;
	for (const pair<string, int>& pair : sorted)
		answer.push_back(stoi(pair.first));
	
	return answer;
}

 

실행 결과

댓글