DuckingRacoon
프로그래머스 | [연습문제] 완주하지 못한 선수 본문
출처
🌐 코딩테스트 연습 - 완주하지 못한 선수 | 프로그래머스 스쿨
문제
문제 설명
수많은 마라톤 선수들이 마라톤에 참여하였습니다. 단 한 명의 선수를 제외하고는 모든 선수가 마라톤을 완주하였습니다.
마라톤에 참여한 선수들의 이름이 담긴 배열 participant와 완주한 선수들의 이름이 담긴 배열 completion이 주어질 때, 완주하지 못한 선수의 이름을 return 하도록 solution 함수를 작성해주세요.
제한사항
- 마라톤 경기에 참여한 선수의 수는 1명 이상 100,000명 이하입니다.
- completion의 길이는 participant의 길이보다 1 작습니다.
- 참가자의 이름은 1개 이상 20개 이하의 알파벳 소문자로 이루어져 있습니다.
- 참가자 중에는 동명이인이 있을 수 있습니다.
입출력 예시
participant completion return
| ["leo", "kiki", "eden"] | ["eden", "kiki"] | "leo" |
| ["marina", "josipa", "nikola", "vinko", "filipa"] | ["josipa", "filipa", "marina", "nikola"] | "vinko" |
| ["mislav", "stanko", "mislav", "ana"] | ["stanko", "ana", "mislav"] | "mislav" |
풀이
1차 풀이 (성공)
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
string solution(vector<string> participant, vector<string> completion)
{
// 0. participant의 크기가 1이고 completion이 0인 경우 (edge case 확인)
if (participant.size() == 1) // 처음에 이 조건 까먹음
return participant[0];
// 1.
sort(participant.begin(), participant.end());
sort(completion.begin(), completion.end());
// 2.
for (int i = 0; i < completion.size(); i++)
{
if (participant[i] != completion[i])
return participant[i];
}
// 3.
return participant[participant.size()-1];
}
2차 풀이 (실패)
바이너리 서치로 구현 해보려 했으나…
안 된다 ㅜㅠ 왜일까?
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
string solution(vector<string> participant, vector<string> completion)
{
// Sort both lists
sort(participant.begin(), participant.end());
sort(completion.begin(), completion.end());
int left = 0, right = completion.size(); // completion.size() < participant.size()
// Perform binary search
while (left < right)
{
int mid = (left + right) / 2;
// Check if there's a mismatch at the midpoint
if (participant[mid] == completion[mid])
{
// Move to the right part
left = mid + 1;
}
else
{
// Move to the left part
right = mid;
}
}
// At the end of the loop, `left` will point to the missing participant
return participant[left];
}
3차 풀이
#include <string>
#include <vector>
#include <unordered_map>
using namespace std;
string solution(vector<string> participant, vector<string> completion)
{
unordered_map<string, int> maps;
// 1. maps에
for (const auto& parti : participant)
{
if (maps.count(parti) != 0)
maps[parti] += 1;
else
maps[parti] = 1;
}
// 2.
for (const auto& comp : completion)
{
maps[comp] -= 1;
if ( maps[comp] < 1)
{
maps.erase(comp);
}
}
// 3.
return maps.begin()->first;
// return (*maps.begin()).first; // 굳이 이런 식으로...?
}
'알고리즘' 카테고리의 다른 글
| 프로그래머스 | [연습문제] 의상 (1) | 2025.09.01 |
|---|---|
| 프로그래머스 | [연습문제] 전화번호 목록 (0) | 2025.09.01 |
| 프로그래머스 | [연습문제] 폰켓몬 (1) | 2025.09.01 |
| 프로그래머스 | [연습문제] 단어변환 (1) | 2025.09.01 |
| 프로그래머스 | [연습문제] 아이템 줍기 (1) | 2025.09.01 |