์•Œ๊ณ ๋ฆฌ์ฆ˜

ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค ํ•ด์‹œ - ์™„์ฃผํ•˜์ง€ ๋ชปํ•œ ์„ ์ˆ˜

ghtis1798 2021. 6. 27. 17:13

๐Ÿ”ธ ๋ฌธ์ œ ์ ‘๊ทผ ๋ฐฉ์‹

โ— ํ’€์ด ์„ฑ๊ณต, ์‹œ๊ฐ„ ์ดˆ๊ณผ

  1. participant, completion์„ Queue์— ๋„ฃ๋Š”๋‹ค.
  2. completion์„ ๊บผ๋‚ด participant์— ์žˆ์œผ๋ฉด participant์—์„œ ์ œ๊ฑฐํ•œ๋‹ค.
  3. completion ์š”์†Œ๊ฐ€ ์—†์–ด์งˆ๋•Œ๊นŒ์ง€ ๋ฐ˜๋ณตํ•˜๊ณ  ๋‚จ์•„์žˆ๋Š” participant๋ฅผ ๋ฐ˜ํ™˜ํ•œ๋‹ค.

→ ์ด ๋ฌธ์ œ์˜ ๊ฒฝ์šฐ ๋‹ต์„ ๊ตฌํ•  ์ˆ˜๋Š” ์žˆ์ง€๋งŒ, ํšจ์œจ์„ฑ ๋ฌธ์ œ๊ฐ€ ์žˆ์—ˆ๋‹ค.

์‹œ๊ฐ„๋ณต์žก๋„๊ฐ€ O(N^2)์ผ ๊ฒฝ์šฐ ํ†ต๊ณผํ•  ์ˆ˜ ์—†๋‹ค.

โญ• ์‹œ๊ฐ„ ์ดˆ๊ณผ ํ•ด๊ฒฐ

best_solution1, 2๋กœ ํ’€์ด ์‹œ ํšจ์œจ์„ฑ ๋ฌธ์ œ๋ฅผ ํ†ต๊ณผํ•  ์ˆ˜ ์žˆ์—ˆ๋‹ค.

best_solution1์˜ ๊ฒฝ์šฐ, ์ •๋ ฌ ํ›„ ์ตœ๋Œ€ $10^5$๋ฒˆ ๋น„๊ต๋ฅผ ์ˆ˜ํ–‰ํ•˜๊ธฐ ๋•Œ๋ฌธ์— O(N)๋งŒ ์ˆ˜ํ–‰ํ•˜๋ฉด ๋œ๋‹ค.

best_solution2์˜ ๊ฒฝ์šฐ ํ•ด์‹œ๋ฅผ ์‚ฌ์šฉํ•œ ํ’€์ด๋ฐฉ์‹์œผ๋กœ ์‹œ๊ฐ„ ๋‹จ์ถ•์— ํšจ๊ณผ์ ์ด์—ˆ๋‹ค.

๐Ÿ’ง Sourece Code

# 2021.09.05 ์ตœ์‹ ํ’€์ด - hash_map ์‚ฌ์šฉ
from collections import defaultdict

def solution(participant, completion):
    answer = ''
    start = defaultdict(int)
    
    for p in participant:
        start[p] += 1
    
    for c in completion:
        start[c] -= 1
    
    for k, v in start.items():
        if v != 0:
            answer = k  
    
    return answer
=========================================================================
from collections import deque

def solution(participant, completion):
    '''
    Notes: 
    - ํ•ด๋‹น ํ’€์ด๋Š” deque ์‚ฌ์šฉ ์‹œ ์‹œ๊ฐ„์ดˆ๊ณผ ๋ฌธ์ œ๊ฐ€ ๋ฐœ์ƒํ•˜๋Š” ๋ฌธ์ œ๊ฐ€ ์žˆ์—ˆ๋‹ค.
    - ์‹œ๊ฐ„๋ณต์žก๋„ ๊ณ„์‚ฐ ์‹œ O(N^2)์ผ ๊ฒฝ์šฐ ํ†ต๊ณผ๊ฐ€ ์•ˆ๋˜๋„๋ก ์„ค๊ณ„๋˜์–ด ์žˆ๋Š” ๋“ฏ ํ•˜๋‹ค.

        1. participant, completion์„ Queue์— ๋„ฃ๋Š”๋‹ค.
        2. completion์„ ๊บผ๋‚ด participant์— ์žˆ์œผ๋ฉด participant์—์„œ ์ œ๊ฑฐํ•œ๋‹ค.
        3. completion ์š”์†Œ๊ฐ€ ์—†์–ด์งˆ๋•Œ๊นŒ์ง€ ๋ฐ˜๋ณตํ•˜๊ณ  ๋‚จ์•„์žˆ๋Š” participant๋ฅผ ๋ฐ˜ํ™˜ํ•œ๋‹ค.

    Args:
        participant (list): ์ฐธ๊ฐ€์ž ๋ฆฌ์ŠคํŠธ
        completion (list): ์™„์ฃผ์ž ๋ฆฌ์ŠคํŠธ

    Returns:
        answer (str): ์™„์ฃผํ•˜์ง€ ๋ชปํ•œ ์ฐธ๊ฐ€์ž ์ด๋ฆ„

    '''

    answer = ''
    participant = deque(participant)
    completion = deque(completion)

    while completion:
        one = completion.popleft()
        if one in participant:
            participant.remove(one)

    answer = list(participant)
    return answer[0]

def best_solution1(participant, completion):
    answer = ''
    participant.sort()
    completion.sort()

    for p, c in zip(participant, completion):
        if p != c:
            return p

    return participant[-1]

def best_solution2(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

participant = ["leo", "kiki", "eden"]
completion = ["eden", "kiki"]
print(solution(participant, completion))