완주하지 못한 선수 (Python)

0. 출처

1. 기록

  • 22/04/13 (수)

2. 풀이

(1) 아이디어

1. 아이디어
>> 정렬 후 비교해서
>> 다른 경우가 생기는 경우를 return 한다.

2. 시간복잡도
>>

3. 자료구조
>>

(2) 코드

# 풀이1 : 리스트 정렬

def solution(participant, completion):
    p = sorted(participant)
    c = sorted(completion)

    for i in range(0, len(completion)):
        if p[i] != c[i]:
            return p[i]

    return p[-1]
# 풀이2 : hash 이용

def solution(participant, completion):
    hashDict = {}
    sumHash = 0
    # 1. Hash : Participant의 dictionary 만들기
    # 2. Participant의 sum(hash) 구하기
    for part in participant:
        hashDict[hash(part)] = part
        print(hashDict)
        sumHash += hash(part)

    # 3. completion의 sum(hash) 빼기
    for comp in completion:
        sumHash -= hash(comp)

    # 4. 남은 값이 완주하지 못한 선수의 hash 값이 된다
    return hashDict[sumHash]
# 풀이3 : counter 이용

import collections

def solution(participant, completion):
    # 1. participant의 Counter를 구한다
    # 2. completion의 Counter를 구한다
    # 3. 둘의 차를 구하면 정답만 남아있는 counter를 반환한다
    answer = collections.Counter(participant) - collections.Counter(completion)

    # 4. counter의 key값을 반환한다
    return list(answer.keys())[0]

(3) 정리

(4) 참고

참고 풀이
참고 영상

+ Recent posts