본문 바로가기
알고리즘/알고리즘

[C++] 프로그래머스 : 완주하지 못한 선수

by 두둠칫 2022. 1. 3.

1. 벡터 풀이

기본 풀이 이중 for문은 시간초과

두 배열의 크기가 1차이 나는 점을 이용해서 정렬 후 같은 인덱스에 다른 값이 있는 경우 participant 값 반환

끝까지 같을 경우 participant 마지막 원소값 반환

 

2. 해시맵

문제에서 주어진 배열은 순서가 상관없기 때문에 unordered_map이 더 빠름

중복되는 이름이 있을 수 있기에 <string, int> 로 key, value 설정 후 count

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

using namespace std;

string solution(vector<string> participant, vector<string> completion) {
/*
	string answer = "";
    
    sort(participant.begin(), participant.end());
    sort(completion.begin(), completion.end());
    
    int pSize = participant.size();
    for(int i=0; i<pSize; i++){
        if(participant[i]!=completion[i]){
            answer = participant[i];
            break;
        }
    }
  
    if(answer == "")
        answer = participant[pSize-1];
*/    
     unordered_map<string, int> um;
    
     for(string p : participant){
         um[p]++;
     }
     for(string c : completion){
         um[c]--;
     }
    
     for(auto m : um){
         if(m.second > 0){
             answer = m.first;
             break;
         }
     }
    
    return answer;
}