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

Algorithm/Programmers

[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค] ํƒ์š•๋ฒ•(greedy) - ์ฒด์œก๋ณต

๊ฐ์ž ๐Ÿฅ” 2021. 8. 6. 20:16
๋ฐ˜์‘ํ˜•

๋ฌธ์ œ๋งํฌ

 

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

  1. ์šฐ์„  ์—ฌ๋ถ„์„ ๊ฐ–๊ณ  ์žˆ๋Š” ํ•™์ƒ์ด ๋งŒ์•ฝ ๋„๋‚œ์„ ๋‹นํ–ˆ์„ ๋•Œ๋Š” ์•„๋ฌดํ•œํ…Œ๋„ ๋นŒ๋ ค์ค„์ˆ˜๊ฐ€ ์—†๊ธฐ์— lost์™€ reserve์— ๊ฐ™์€ ์ˆซ์ž๊ฐ€ ์žˆ์œผ๋ฉด ์ œ๊ฑฐ ํ•ด์ฃผ๋Š” ๊ณผ์ •๋ถ€ํ„ฐ ๊ฑฐ์ณค๋‹ค.
    ์ง‘ํ•ฉ์€ ์ฐจ์ง‘ํ•ฉ์„ ์ด์šฉํ•ด์„œ ์›ํ•˜๋Š” ์›์†Œ๋ฅผ ๋บ„ ์ˆ˜ ์žˆ๊ธฐ์— ๊ฐ„๋‹จํ•˜๊ฒŒ set (์ง‘ํ•ฉ)์„ ์ด์šฉํ–ˆ๋‹ค.
  2. for ๋ฐ˜๋ณต๋ฌธ์„ ์ด์šฉํ•ด์„œ ์žƒ์–ด๋ฒ„๋ฆฐ ํ•™์ƒ (lost)์„ ํ•œ๋ช…์”ฉ ๋ฝ‘์•„ ๋ณด์•˜๊ณ , ํ•ด๋‹น ํ•™์ƒ์ด reserve์—์„œ ๋นŒ๋ฆด ์ˆ˜์žˆ๋Š”์ง€ ํŒ๋‹จํ–ˆ๋‹ค. ๋งŒ์•ฝ reserve์—์„œ lost์—๊ฒŒ ๋นŒ๋ ค์ค„ ์ˆ˜ ์žˆ๋‹ค๋ฉด, lost ๋ฆฌ์ŠคํŠธ์—์„œ ์‚ญ์ œํ•ด๋ฒ„๋ฆฌ๋Š” ๊ณผ์ •์„ ๊ฑฐ์ณค๋‹ค.
  3. ๋งŒ์•ฝ reserve์—์„œ ๋นŒ๋ ค์ค„ ์ˆ˜์—†๋‹ค๋ฉด, ๊ทธ ํ•™์ƒ์€ ์ˆ˜์—…์„ ๋ชป๋“ฃ๋Š” ๊ฒƒ์ด๊ธฐ์— '์ „์ฒดํ•™์ƒ์ˆ˜'์—์„œ -1 ํ•ด์คฌ๋‹ค. (์–ด์ฐจํ”ผ ์ˆ˜์—…๋“ฃ๋Š” ํ•™์ƒ์€ ์ฒ˜์Œ์— n์œผ๋กœ ์‹œ์ž‘ํ•œ๋‹ค.)
def solution(n, lost, reserve):
    
    n_lost = set(lost) - set(reserve)
    n_reserve = set(reserve) - set(lost)
    
    for i in n_lost:
        if i-1 in n_reserve:
            n_reserve.remove(i-1)
        elif i+1 in n_reserve:
            n_reserve.remove(i+1)
        else: # ๋„๋‚œ๋‹นํ•œ i์—๊ฒŒ ์—ฌ๋ถ„์˜ ์˜ท์„ ๋นŒ๋ ค์ค„ reserve๊ฐ€ ์—†๋‹ค๋ฉด ์ „์ฒด ํ•™์ƒ์ˆ˜ -1
            n -= 1
            
    return n

 

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

๋Œ€๋ถ€๋ถ„ lost ์™€ reserve์˜ ์ฐจ๋ฅผ ์ด์šฉํ•ด์„œ ํ’€์—ˆ๊ณ , ๋ฆฌ์ŠคํŠธ์—์„œ ์‚ญ์ œํ•˜๋Š” ๋ฐฉ์‹์„ ์‚ฌ์šฉํ•œ ๊ฒƒ๊ฐ™๋‹ค. ๋งŽ์€ ์‚ฌ๋žŒ๋“ค์ด ๋น„์Šทํ•œ ๋งฅ๋ฝ์œผ๋กœ ๋ฌธ์ œ๋ฅผ ํ’€์—ˆ๋‹ค. ๋‚˜๋Š” "set"์œผ๋กœ ์ด์šฉํ•ด์„œ ์ฐจ์ง‘ํ•ฉ์„ ์ด์šฉํ•œ๋‹ค๋Š” ๊ฒƒ์„ ์ƒ๊ฐ์„ ๋ชปํ–ˆ๊ธฐ์—, ๊ตฌ๊ธ€๋ง์œผ๋กœ ์ด๋ถ€๋ถ„๋งŒ ์ฐพ์•„์„œ ๋ฌธ์ œ๋ฅผ ํ’€์—ˆ๋‹ค.
์ฒ˜์Œ์—๋Š” for loop๋ฅผ ๋Œ๋ ค์„œ reserve๋‚˜ lost ์•ˆ์—์„œ ํ•ด๋‹น ์ˆซ์ž์˜ ์กด์žฌ ์—ฌ๋ถ€๋ฅผ ํŒŒ์•…ํ•œ ํ›„, ์ƒˆ๋กœ์šด n_lost, n_reserve๋กœ appendํ•ด์ฃผ๋Š” ๊ณผ์ •์„ ์‚ฌ์šฉํ–ˆ๋Š”๋ฐ, ๋ฐ˜๋ณต๋ฌธ์ด ๋‘๊ฐœ๋‚˜ ์ƒ๊ฒจ์„œ ์‹œ๊ฐ„๋ณต์žก๋„ ํšจ์œจ์ด ๋งค์šฐ ๋‚ฎ์•˜์„ ๊ฒƒ์ด๋‹ค. ์ฐจ์ง‘ํ•ฉ์„ ์ด์šฉํ•จ์œผ๋กœ์จ ๊ฐ„๋‹จํ•˜๊ฒŒ ์ฒ˜๋ฆฌ ํ•  ์ˆ˜ ์žˆ๋‹ค๋Š” ๊ฒƒ์„ ๋ฐฐ์› ๋‹ค.

๋ฐ˜์‘ํ˜•