티스토리 뷰

반응형


#. Problem


* The copyright in this matter is in Programmers


수많은 마라톤 선수들이 마라톤에 참여하였습니다. 단 한 명의 선수를 제외하고는 모든 선수가 마라톤을 완주하였습니다.


마라톤에 참여한 선수들의 이름이 담긴 배열 participant와 완주한 선수들의 이름이 담긴 배열 completion이 주어질 때, 완주하지 못한 선수의 이름을 return 하도록 solution 함수를 작성해주세요.


#. Resolution Process

  1. Read and understand problem

  2. Redefine the problem + abstract

    - 단 한명의 선수를 제외하고 모든 선수가 완주

  3. Create solution plan (select Algorithm, Data structure)

    - hash(dictionary in python)

  4. Prove the plan (check performance time and usage memory)

  5. Carry out the plan

  6. Look back on the plan and find a way to improve it


#. Solve

   1. dictionary에 participant 정보를 저장, {'name' : 0} -> dictionary는 key값 중복이 불가하여 동명이인이 있을 경우 불가

   2. completion에 participant의 정보가 있는지 확인, 있다면 dictionary의 value값을 1로 수정

      동명이인일 경우(이미 value 값이 1인 경우) return

   3. finally, value값이 0인 key를 return

   1. participant와 completino을 정렬 후 한 요소씩 비교

   2. 만일 요소가 다를 경우 해당 index의 participant가 poor runner.

   3. 모든 요소가 같은 경우 제일 마지막 index가 poor runner.


#. Code

1
2
3
4
5
6
7
8
9
def solution(participant, completion):
    participant.sort()
    completion.sort()
 
    for pn, cn in zip(participant, completion):
        if pn != cn:
            return pn
 
    return participant[-1]
cs



#. Others code

1
2
3
4
5
import collections
 
def solution(participant, completion):
    answer = collections.Counter(participant) - collections.Counter(completion)
    return list(answer.keys())[0]
cs


  - collection.Counter() 은 컨테이너에 동일한 값의 자료가 몇개인지 파악하는데 사용

    (참고 : https://docs.python.org/3/library/collections.html)



1
2
3
4
5
6
7
8
9
10
11
12
def solution(participant, completion):
    answer = ''
    temp = 0
    dic = {}
    for part in participant:
        dic[hash(part)] = part
        temp += int(hash(part))
    for com in completion:
        temp -= hash(com)
    answer = dic[temp]
 
    return answer
cs
  - 1. dictionary에 {hash address, name} 형식으로 저장하여 participant 요소에 해당하는 hash address를 temp 변수에 계속 더함

    2. completion 요소에 해당하는 hash address를 temp 변수에서 계속 빼주면 남은 요소의 address가 남음 (hash address의 가감법)


1
2
3
4
5
6
7
def solution(participant, completion):
    participant.sort()
    completion.sort()
    for i in range(len(completion)):
        if participant[i] != completion[i]:
            return participant[i]
    return participant[len(participant)-1]
cs

반응형

'PS > Problem_Solving' 카테고리의 다른 글

[Programmers] camouflage(hash).py  (0) 2020.01.02
[Programmers] Telephone number list(hash).py  (0) 2020.01.02
[Algospot] QUADTREE (분할 정복)  (0) 2019.09.15
[Algospot] CLOCKSYNC (최적화)  (0) 2019.09.07
[Algospot] BOARDCOVER (탐색)  (0) 2019.09.06
댓글
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday