완주하지 못한 선수
문제
구해야 할 것은 완주하지 못한 자를 골라내는 것이다. 즉, completion 배열에는 없고 participant 배열에는 있는 사람을 찾으면 된다.
처음 생각한 것은 아래와 같다.
1) participant를 map에 저장하면서, key는 참가자 이름, value는 동명이인이 이미 존재한다면 +1, 없으면 1로 넣어준다.
for (let person of participant){
if(!map.get(person)){
map.set(person, 1);
}else{
map.set(person, map.get(person)+1);
}
}
2) completion을 돌면서 한 명씩 map의 해당하는 이름의 값이 1이면 엘리먼트를 삭제, 2 이상이라면 -1 해준다.
for(let person of completion){
if(map.get(person) >= 2){
map.set(person, map.get(person) - 1);
} else {
map.delete(person);
}
}
3) 마지막 남은 원소를 리턴해준다.
for(let person of participant){
if(map.get(person) && map.get(person) >= 1 ){
answer = person;
}
}
function solution(participant, completion) {
let answer = ''
const map = new Map();
for (let person of participant){
if(!map.get(person)){
map.set(person, 1);
}else{
map.set(person, map.get(person)+1);
}
}
for(let person of completion){
if(map.get(person) >= 2){
map.set(person, map.get(person) - 1);
} else {
map.delete(person);
}
}
for(let person of participant){
if(map.get(person) && map.get(person) >= 1 ){
answer = person;
}
}
return answer
}