๐ŸŒฑ → ๐ŸŒณ

[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค] ๋” ๋งต๊ฒŒ - python ๋ณธ๋ฌธ

Algorithms

[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค] ๋” ๋งต๊ฒŒ - python

BAY 2023. 8. 2. 15:35
728x90

์ฝ”๋“œ

์‹œ๊ฐ„์ดˆ๊ณผ ์ฝ”๋“œ

from collections import deque
def solution(scoville, K):
    answer = 0
    scoville = deque(scoville)
    while True:
        scoville = deque(sorted(scoville))
        if scoville[0] >= K:
            break
        v1 = scoville.popleft()
        v2 = scoville.popleft()
        scoville.append(v1+(v2*2))
        answer += 1
    return answer

์‹ฌ์ง€์–ด ๋ช‡๋ช‡ํ…Œ์ŠคํŠธ ๋Ÿฐํƒ€์ž„์—๋Ÿฌ๋„ ๋ฐœ์ƒ

deque ์‚ฌ์šฉํ•ด์„œ ์ƒˆ๋กœ์šด ์Šค์ฝ”๋นŒ์ง€์ˆ˜ ๋“ค์–ด์˜ฌ ๋•Œ ๋งˆ๋‹ค ์ •๋ ฌํ•ด์คŒ 

๋‚ด๊ฐ€ ๋ด๋„ ๊ตฌ๋ฆฐ ์ฝ”๋“œ .. 

 

 

์‹œ๊ฐ„์ดˆ๊ณผ ํ•ด๊ฒฐ ์ฝ”๋“œ

from heapq import heapify, heappush, heappop
def solution(scoville, K):
    answer = 0
    heapify(scoville)
    while True:
        if scoville[0] >= K:
            break
        v1 = heappop(scoville)
        v2 = heappop(scoville)
        heappush(scoville, v1+(v2*2))
        answer += 1
    return answer

์ตœ์†Œํž™์„ ์ด์šฉํ•ด์„œ ์‹œ๊ฐ„์ดˆ๊ณผ๋Š” ํ•ด๊ฒฐํ–ˆ์ง€๋งŒ ๋ช‡ ๊ฐœ์˜ ํ…Œ์ŠคํŠธ์—์„œ ๋Ÿฐํƒ€์ž„์—๋Ÿฌ ๋ฐœ์ƒ

 

ํ•ด๊ฒฐ

from heapq import heapify, heappush, heappop
def solution(scoville, K):
    answer = 0
    heapify(scoville)
    while True:
        if scoville[0] >= K:
            break
        if len(scoville) <= 1 and scoville[0] < K:
            return -1
        v1 = heappop(scoville)
        v2 = heappop(scoville)
        heappush(scoville, v1+(v2*2))
        answer += 1
    return answer

์•„์•™ ๋ฌธ์ œ ์ œ๋Œ€๋กœ ์•ˆ์ฝ์–ด์„œ ๊ทธ๋Ÿผ

๋ชจ๋“  ์Œ์‹์˜ ์Šค์ฝ”๋นŒ ์ง€์ˆ˜๋ฅผ K ์ด์ƒ์œผ๋กœ ๋งŒ๋“ค ์ˆ˜ ์—†๋Š” ๊ฒฝ์šฐ์—๋Š” -1์„ return ํ•ฉ๋‹ˆ๋‹ค. ๋ถ€๋ถ„ ์ ์šฉํ•ด์ฃผ๋‹ˆ ๋ฌธ์ œ ํ•ด๊ฒฐ๋จ

 

์ฐธ๊ณ ์ž๋ฃŒ

https://www.daleseo.com/python-heapq/

728x90