[Leetcode] 42. Trapping Rain Water

Beanxxยท2022๋…„ 3์›” 22์ผ
0

Algorithm

๋ชฉ๋ก ๋ณด๊ธฐ
10/10
post-thumbnail

'ํŒŒ์ด์ฌ ์•Œ๊ณ ๋ฆฌ์ฆ˜ ์ธํ„ฐ๋ทฐ' ์ฑ…์œผ๋กœ ์ฝ”๋”ฉํ…Œ์ŠคํŠธ ๊ณต๋ถ€ํ•˜๋‹ค๊ฐ€ ํ’€์ด๋ฅผ ๋ด๋„ ์ดํ•ด๊ฐ€ ๊ฐ€์ง€ ์•ˆํ•˜๋Š” ๋ถ€๋ถ„์ด ์žˆ์–ด ์ผ๋‹จ ๊ธฐ๋กํ•ด๋‘๊ณ  ๋‚˜์ค‘์— ๋‹ค์‹œ ์ฐจ๊ทผ์ฐจ๊ทผ ์ดํ•ดํ•˜๋ ค๊ณ  ๋‚จ๊ฒจ๋‘๊ธฐ!

  1. Trapping Rain Water
    ๋†’์ด๋ฅผ ์ž…๋ ฅ๋ฐ›์•„ ๋น„ ์˜จ ํ›„ ์–ผ๋งˆ๋‚˜ ๋งŽ์€ ๋ฌผ์ด ์Œ“์ผ ์ˆ˜ ์žˆ๋Š”์ง€ ๊ณ„์‚ฐํ•˜๋ผ.

1๋ฒˆ์งธ ๋ฐฉ๋ฒ•. ํˆฌ ํฌ์ธํ„ฐ๋ฅผ ์ตœ๋Œ€๋กœ ์ด๋™

์ด ๋ฐฉ๋ฒ• ๋‹ค๋ฅธ ๋ธ”๋กœ๊ทธ ๊ธ€์„ ํ†ตํ•ด ์ดํ•ด๊ฐ€ ๋˜์—ˆ๋‹ค.

class Solution:
    def trap(self, height: List[int]) -> int:
        if not height:
            return 0
        
        volume = 0
        left, right = 0, len(height)-1
        left_max, right_max = height[left], height[right]
        
        while left < right:
            left_max, right_max = max(height[left], left_max), max(height[right], right_max)
           
            # ๋” ๋†’์€ ์ชฝ์„ ํ–ฅํ•ด ํˆฌ ํฌ์ธํ„ฐ ์ด๋™
            if left_max <= right_max:
                volume += left_max - height[left]
                left += 1
            else:
                volume += right_max -height[right]
                right -= 1
        return volume

2๋ฒˆ์งธ ๋ฐฉ๋ฒ•. ์Šคํƒ ์Œ“๊ธฐ

class Solution:
    def trap(self, height: List[int]) -> int:
        stack = []
        volume = 0  # ์ฑ„์›Œ์ง€๋Š” ๋ฌผ ๋ˆž์ด
        
        for i in range(len(height)):
            # ๋ณ€๊ณก์ ์„ ๋งŒ๋‚˜๋Š” ๊ฒฝ์šฐ
            while stack and height[i] > height[stack[-1]]:  # stack[-1]: ์Šคํƒ์—์„œ ์›์†Œ๋ฅผ ์ œ๊ฑฐํ•˜์ง€ ์•Š๊ณ  ๊ฐ€์ ธ์˜ค๊ธฐ๋งŒ ํ•  ๋•Œ ์‚ฌ์šฉ
                # ์Šคํƒ์—์„œ ๊บผ๋‚ธ๋‹ค
                top = stack.pop()
                    
                if not len(stack):
                    break
                    
                # ์ด์ „๊ณผ์˜ ์ฐจ์ด๋งŒํผ ๋ฌผ ๋†’์ด ์ฒ˜๋ฆฌ
                distance = i - stack[-1] -1
                waters = min(height[i], height[stack[-1]]) - height[top]
                    
                volume += distance * waters
                
            stack.append(i)
        return volume
profile
FE developer

0๊ฐœ์˜ ๋Œ“๊ธ€