
programmers.co.kr/learn/courses/30/lessons/42576
코딩테스트 연습 - 완주하지 못한 선수
수많은 마라톤 선수들이 마라톤에 참여하였습니다. 단 한 명의 선수를 제외하고는 모든 선수가 마라톤을 완주하였습니다. 마라톤에 참여한 선수들의 이름이 담긴 배열 participant와 완주한 선수
programmers.co.kr
[문제 풀이]
map을 이용하여 문제를 풀었습니다.
이 문제는 마라톤에 참여한 선수 중에 완주를 하지 못한 지원자를 찾는 문제입니다. 지원자 중에 동명이인이 존재 할 수도 있습니다. 문제를 푸는 방식은 입력으로 주어진 competition 벡터를 map에 넣어 이름들을 세어줍니다. 그 후 participant 백터를 순회하며 존재하면 빼주고 map에 존재하지 않거나 0인 경우 그 이름을 반환해 줍니다.
[c++]
#include <string>
#include <vector>
#include<map>
using namespace std;
string solution(vector<string> participant, vector<string> completion) {
map<string, int> runner;
for(auto item : completion){
if(runner.find(item) == runner.end())
runner[item] = 1;
else
runner[item]++;
}
for(auto item : participant)
if(runner[item] == NULL || runner[item] == 0)
return item;
else
runner[item]--;
}
[java]
import java.util.*;
class Solution{
public String solution(String[] participant, String[] completion) {
String answer = "";
HashMap<String, Integer> participantMap = new HashMap<>();
for(String s : participant)
participantMap.put(s, participantMap.getOrDefault(s, 0) + 1);
for(String s: completion) {
if(participantMap.get(s) == 1)
participantMap.remove(s);
else
participantMap.put(s, participantMap.get(s) - 1);
}
Iterator<String> it = participantMap.keySet().iterator();
answer = it.next();
return answer;
}
}
'algorithm > 프로그래머스' 카테고리의 다른 글
프로그래머스_베스트앨범(C++, JAVA) (0) | 2020.12.28 |
---|---|
프로그래머스_전화번호 목록(C++, JAVA) (0) | 2020.11.23 |
프로그래머스_주식가격(C++, JAVA) (0) | 2020.11.10 |
프로그래머스_위장(C++, JAVA) (0) | 2020.11.10 |
프로그래머스_네트워크(C++) (0) | 2020.10.21 |