프로그래머스 문제풀이
완주하지 못한 선수(Python, Js)
codermun
2021. 6. 22. 21:38
728x90
반응형
파이썬
이전 풀이
해시 함수를 이용해 count 값의 차이로 완주하지 못한 한명을 찾아낸다.
def solution(participant, completion):
answer = ''
A = {}
count = 0
for part in participant:
A[hash(part)] = part
count += int(hash(part))
for com in completion:
count -= int(hash(com))
answer = A[count]
return answer
def solution(participant, completion):
answer = ''
my_dict = {}
count = 0
for part in participant:
my_dict[hash(part)] = part
count += hash(part)
for key in completion:
count -= hash(key)
#남은 카운트를 이용해 한 명을 찾는다.
answer = my_dict[count]
return answer

이후 풀이
카운터 객체로 딕셔너리를 효율적으로 구성한 후
동일 키 값이 존재할 경우 value의 값을 -1 씩 줄인다.
이후 value ==1 이라는 의미는 완주하지 못한 한명이라는 의미로 key가 곧 완주하지 못한 한명의 이름이 된다.
from collections import Counter
def solution(participant, completion):
answer = ''
my_dict = Counter(participant)
for key in completion:
if key in my_dict:
my_dict[key] = my_dict[key] -1
for key, value in my_dict.items():
if value == 1:
answer = key
return answer

자바스크립트
function solution(participant, completion) {
const sortedPar = participant.sort()
const sortedCom = completion.sort()
for (const [idx,element] of sortedPar.entries()){
if (!sortedCom[idx] || sortedCom[idx] !== element){
return element
}
}
}

728x90
반응형