Potato
์•ˆ๋…•ํ•˜์„ธ์š”, ๊ฐ์žก๋‹ˆ๋‹ค?๐Ÿฅ” ^___^ ๐Ÿ˜บ github ๋ฐ”๋กœ๊ฐ€๊ธฐ ๐Ÿ‘‰๐Ÿป

Algorithm/Programmers

[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค] ํ•ด์‹œ-์™„์ฃผํ•˜์ง€ ๋ชปํ•œ ์„ ์ˆ˜ ( level.1)

๊ฐ์ž ๐Ÿฅ” 2021. 9. 6. 23:13
๋ฐ˜์‘ํ˜•

 

๋ฌธ์ œ ๋งํฌ

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

 

์ฝ”๋”ฉํ…Œ์ŠคํŠธ ์—ฐ์Šต - ์™„์ฃผํ•˜์ง€ ๋ชปํ•œ ์„ ์ˆ˜

์ˆ˜๋งŽ์€ ๋งˆ๋ผํ†ค ์„ ์ˆ˜๋“ค์ด ๋งˆ๋ผํ†ค์— ์ฐธ์—ฌํ•˜์˜€์Šต๋‹ˆ๋‹ค. ๋‹จ ํ•œ ๋ช…์˜ ์„ ์ˆ˜๋ฅผ ์ œ์™ธํ•˜๊ณ ๋Š” ๋ชจ๋“  ์„ ์ˆ˜๊ฐ€ ๋งˆ๋ผํ†ค์„ ์™„์ฃผํ•˜์˜€์Šต๋‹ˆ๋‹ค. ๋งˆ๋ผํ†ค์— ์ฐธ์—ฌํ•œ ์„ ์ˆ˜๋“ค์˜ ์ด๋ฆ„์ด ๋‹ด๊ธด ๋ฐฐ์—ด participant์™€ ์™„์ฃผํ•œ ์„ ์ˆ˜

programmers.co.kr

 

๋‚˜์˜ ํ’€์ด

์ผ๋ฐ˜์ ์œผ๋กœ ๊ตฌํ˜„๋ฐฉ์‹๋ง๊ณ  "ํ•ด์‹œ"๋ผ์„œ ์ตœ๋Œ€ํ•œ dic์„ ํ™œ์šฉํ•ด์„œ ํ’€๋ ค๊ณ  ๋…ธ๋ ฅํ•ด๋ดค๋‹ค. ํ™•์‹คํžˆ ํšจ์œจ์„ฑ, ์‹œ๊ฐ„๋ณต์žก๋„ ์ธก๋ฉด์—์„œ key๊ฐ’์„ ํ™œ์šฉํ•œ hash ๋ฐฉ๋ฒ•์ด ์ข‹์€ ๊ฒƒ ๊ฐ™๋‹ค!!

  1. hash๋Š” ๋ชจ๋“  ๊ฐ’์„ ์ˆซ์ž๋กœ? ์ฒ˜๋ฆฌ 
  2. hash ๊ฐ’์„ key๊ฐ’์œผ๋กœ ๊ฐ–๊ณ  ์ด๋ฆ„์„ value๊ฐ’์œผ๋กœ ๊ฐ–๋Š” ๋”•์…”๋„ˆ๋ฆฌ๋ฅผ ์ƒ์„ฑ
  3. participant ์— ์žˆ๋Š” ๋ชจ๋“  ์ด๋ฆ„์˜ hash๊ฐ’์„ hash_num์ด๋ผ๋Š” ๋ณ€์ˆ˜์— ๋”ํ•ด์ค€๋‹ค.
  4. participant์— ์žˆ์ง€๋งŒ completion์—๋Š” ์—†๋Š” ์ด๋ฆ„์„ ์ฐพ์•„์•ผ ํ•˜๊ธฐ์— participant์— ์žˆ๋Š” ๋ชจ๋“  ๊ฐ’์„ ๋”ํ•œ hash_num์—์„œ completion์— ์žˆ๋Š” ์ด๋ฆ„๋“ค์„ ๋นผ์ค€๋‹ค.
  5. ๊ทธ๋Ÿผ hash_num์— ๋‚จ์€ ์ˆซ์ž๋Š” ์™„์ฃผํ•˜์ง€ ๋ชปํ•œ ์„ ์ˆ˜์˜ ์ด๋ฆ„์„value๊ฐ’์œผ๋กœ ๊ฐ–๋Š” key๊ฐ’์ด ๋ ๊ฒƒ
def solution(participant, completion):
    dic = {}
    hash_num = 0
    for p in participant:
        dic[hash(p)] = p #hash๊ฐ’:key, p:value
        hash_num +=  int(hash(p))
    for c in completion:
        hash_num -= int(hash(c))
    
    return dic[hash_num]

 

๋‹ค๋ฅธ์‚ฌ๋žŒํ’€์ด

https://programmers.co.kr/learn/courses/30/lessons/42576/solution_groups?language=python3 

 

ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค

์ฝ”๋“œ ์ค‘์‹ฌ์˜ ๊ฐœ๋ฐœ์ž ์ฑ„์šฉ. ์Šคํƒ ๊ธฐ๋ฐ˜์˜ ํฌ์ง€์…˜ ๋งค์นญ. ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค์˜ ๊ฐœ๋ฐœ์ž ๋งž์ถคํ˜• ํ”„๋กœํ•„์„ ๋“ฑ๋กํ•˜๊ณ , ๋‚˜์™€ ๊ธฐ์ˆ  ๊ถํ•ฉ์ด ์ž˜ ๋งž๋Š” ๊ธฐ์—…๋“ค์„ ๋งค์นญ ๋ฐ›์œผ์„ธ์š”.

programmers.co.kr

ํ•ด์‹œ ์•Œ๊ณ ๋ฆฌ์ฆ˜์„ ์‚ฌ์šฉํ•ด์„œ ํ’€๋ ค๊ณ  ๋…ธ๋ ฅํ–ˆ๋”๋‹ˆ ๋‚˜๋ž‘ ๋น„์Šทํ•˜๊ฒŒ ํ•ด์‹œ์•Œ๊ณ ๋ฆฌ์ฆ˜์„ ์‚ฌ์šฉํ•ด์„œ ํ‘ผ ์‚ฌ์šฉ์ž๊ฐ€ ๋งŽ์•˜๋‹ค. ๋ฟŒ๋“ฏํ–ˆ๋‹ค ^0^ ๊ทธ๋ฆฌ๊ณ  ๋Œ€๋ถ€๋ถ„ ์ด๋Ÿฐ ๋ฌธ์ œ๋Š” sort() ํ•ด์„œ ํšจ์œจ์„ ๋†’์ธ๋‹ค๊ณ  ํ•œ๋‹ค. sortํ•˜๋ฉด ํšจ์œจ์ด ๋†’์•„์ง€๋‚˜...?

์ด์™ธ์—๋„ zipํ•จ์ˆ˜, Counterํ•จ์ˆ˜๋ฅผ ์ด์šฉํ•ด์„œ ํ‘ผ ํ’€์ด๋ฐฉ๋ฒ•์ด ํšจ์œจ์„ฑ์ ์ธ ์ธก๋ฉด์—์„œ ๋†’๊ฒŒ ์ ์ˆ˜๋ฅผ ๋†’๊ฒŒ ๋ฐ›์•˜๋‹ค. ์•„๋ฌด๋ฆฌ ํ•ด์‹œ ์•Œ๊ณ ๋ฆฌ์ฆ˜ ๋ฌธ์ œ์ง€๋งŒ ์—ญ์‹œ ์ ‘๊ทผํ•˜๋Š” ๋ฐฉ๋ฒ•์œผ ๋„ˆ๋ฌด ๋งŽ๋‹ค!

Counter ํ•จ์ˆ˜ ์ด์šฉ

import collections


def solution(participant, completion):
    answer = collections.Counter(participant) - collections.Counter(completion)
    return list(answer.keys())[0]

 

zip ํ•จ์ˆ˜ ์ด์šฉ

def solution(participant, completion):
    participant.sort()
    completion.sort()
    for p, c in zip(participant, completion):
        if p != c:
            return p
    return participant[-1]

 

๋ฐ˜์‘ํ˜•