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

cheeeese·2022년 1월 31일
0

코딩테스트 연습

목록 보기
37/151
post-thumbnail

📖 문제

https://programmers.co.kr/learn/courses/30/lessons/42576

💻 코드

def solution(participant, completion):
    answer = ''
    
    participant.sort()
    completion.sort()
    
    for i in range(len(completion)):
        if participant[i]!=completion[i]:
            return participant[i]
    
    return participant[len(participant)-1]

➕ 추가

처음 제출했던 코드

def solution(participant, completion):
    answer = ''
    
    for p in participant:
        if p in completion:
            completion.remove(p)
        else:
            answer=p
            
    return answer

  • 정확성 테스트는 통과했지만 효율성 테스트는 통과하지 못함

  • 다음으로 위의 코드를 제출함 -> 통과

    • 먼저 participantcompletion 모두 sort
    • for문을 돌리면서 participant[i]completion[i] 가 다르다면 그 participant가 완주하지 못한 것이므로 출력
    • 끝까지 돌려도 없다다면 마지막 주자가 완주하지 못한 것이므로 participant[len(participant)-1] 출력

#### 해시를 사용하여 해결하는 방법 (다른사람 풀이+구글링) ``` def solution(participant, completion): answer = '' temp = 0 dic = {} # 1. Hash : Participant의 dictionary 만들기 # 2. Participant의 sum(hash) 구하기 for part in participant: dic[hash(part)] = part temp += int(hash(part)) # 3. completion의 sum(hash) 빼기 for com in completion: temp -= hash(com) # 4. 남은 값이 완주하지 못한 선수의 hash 값이 된다 answer = dic[temp]
return answer

0개의 댓글