[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค/python] ํ•ด์‹œ(Hash) : ์™„์ฃผํ•˜์ง€ ๋ชปํ•œ ์„ ์ˆ˜

2021. 3. 23. 23:17

๋ฌธ์ œ ์„ค๋ช…

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

๋งˆ๋ผํ†ค์— ์ฐธ์—ฌํ•œ ์„ ์ˆ˜๋“ค์˜ ์ด๋ฆ„์ด ๋‹ด๊ธด ๋ฐฐ์—ด participant์™€ ์™„์ฃผํ•œ ์„ ์ˆ˜๋“ค์˜ ์ด๋ฆ„์ด ๋‹ด๊ธด ๋ฐฐ์—ด completion์ด ์ฃผ์–ด์งˆ ๋•Œ, ์™„์ฃผํ•˜์ง€ ๋ชปํ•œ ์„ ์ˆ˜์˜ ์ด๋ฆ„์„ return ํ•˜๋„๋ก solution ํ•จ์ˆ˜๋ฅผ ์ž‘์„ฑํ•ด์ฃผ์„ธ์š”.

 

์ œํ•œ์‚ฌํ•ญ

  • ๋งˆ๋ผํ†ค ๊ฒฝ๊ธฐ์— ์ฐธ์—ฌํ•œ ์„ ์ˆ˜์˜ ์ˆ˜๋Š” 1๋ช… ์ด์ƒ 100,000๋ช… ์ดํ•˜์ž…๋‹ˆ๋‹ค.
  • completion์˜ ๊ธธ์ด๋Š” participant์˜ ๊ธธ์ด๋ณด๋‹ค 1 ์ž‘์Šต๋‹ˆ๋‹ค.
  • ์ฐธ๊ฐ€์ž์˜ ์ด๋ฆ„์€ 1๊ฐœ ์ด์ƒ 20๊ฐœ ์ดํ•˜์˜ ์•ŒํŒŒ๋ฒณ ์†Œ๋ฌธ์ž๋กœ ์ด๋ฃจ์–ด์ ธ ์žˆ์Šต๋‹ˆ๋‹ค.
  • ์ฐธ๊ฐ€์ž ์ค‘์—๋Š” ๋™๋ช…์ด์ธ์ด ์žˆ์„ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

 

์ •๋‹ต

def solution(participant, completion):
    answer = "_"
    d = {}
    for i in participant:
        if i in d:
            d[i] += 1
        else:
            d[i] = 1

    for c in completion:
        d[c] -= 1

    for k, v in d.items():
        if v != 0:
            answer = k

    return answer

d = {}
    for i in participant:
        if i in d:
            d[i] += 1
        else:
            d[i] = 1

์ฐธ์—ฌํ•œ ์„ ์ˆ˜๋“ค์˜ ์ด๋ฆ„์„ d์— ํ‚ค๋กœ ์ €์žฅํ•˜๊ณ  ๊ฐ’์—๋Š” 1์„ ์ €์žฅํ•œ๋‹ค.

๊ฐ™์€ ์ด๋ฆ„์ด ์žˆ๋‹ค๋ฉด (if i in d) ๊ฐ’์— 1์„ ๋”ํ•œ๋‹ค.

์ฆ‰, ํ‚ค๋Š” ์„ ์ˆ˜์˜ ์ด๋ฆ„์ด ๋˜๊ณ  ๊ฐ’์€ ํ•ด๋‹น ์ด๋ฆ„์„ ๊ฐ€์ง„ ์‚ฌ๋žŒ ์ˆ˜๊ฐ€ ๋œ๋‹ค.

for c in completion:
        d[c] -= 1

์™„์ฃผํ•œ ์„ ์ˆ˜์˜ ์ด๋ฆ„์„ ํ‚ค๋กœ ๊ฐ€์ง„ ๊ฐ’์„ 1์”ฉ ๋นผ์ค€๋‹ค.

ํ•ด๋‹น ์ด๋ฆ„์„ ๊ฐ€์ง„ ์„ ์ˆ˜๊ฐ€ 1๋ช…์ด๋ผ๋ฉด ๊ฐ’์ด 0์ด ๋ ํ…Œ๊ณ  n๋ช…์ด๋ผ๋ฉด n-1์ด ๋  ๊ฒƒ์ด๋‹ค.

for k, v in d.items():
        if v != 0:
            answer = k

๊ฐ’์ด 0์ด ์•„๋‹ˆ๋ผ๋Š” ๊ฒƒ์€ ์™„์ฃผํ•˜์ง€ ๋ชปํ•œ ์‚ฌ๋žŒ์ด๋ผ๋Š” ๋œป์ด๋ฏ€๋กœ

๊ฐ’์ด 0์ด ์•„๋‹Œ ํ‚ค๋ฅผ answer์— ์ €์žฅํ•œ ํ›„ returnํ•œ๋‹ค.

728x90

BELATED ARTICLES

more