본문 바로가기
Python/코딩테스트

[Leetcode] 42.Trappling Rainbow Water

by 좋은데이피치 2021. 6. 17.
728x90

빗물 트래핑

 - 문제 : 높이를 입력받아 비 온 후 얼마나 많은 물이 쌓일 수 있는지 계산하라.

 https://leetcode.com/problems/trapping-rain-water/

Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it can trap after raining.

 

Example 1:

Input: height = [0,1,0,2,1,0,1,3,2,1,2,1] Output: 6 Explanation: The above elevation map (black section) is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped.

Example 2:

Input: height = [4,2,0,3,2,5] Output: 9

 

Constraints:

  • n == height.length
  • 0 <= n <= 3 * 104
  • 0 <= height[i] <= 105

 

풀이 1. 투 포인터를 최대로 이동

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. 스택 쌓기

    def trap(self, height: List[int]) -> int:
        stack = []
        volume = 0

        for i in range(len(height)):
            # 변곡점을 만나는 경우
            while stack and height[i] > height[stack[-1]]:
                #스택에서 꺼낸다.
                top = stack.pop()

                if not len(stack):
                    break

                #d이전과의 차이만큼 물 높이 처리
                distance = i - stack[-1] -1
                waters = min(height[i], height[stack[-1]]) - height[top]

                volume += distance * waters
        
        stack.append(i)
    return volume

 

 

 

728x90

'Python > 코딩테스트' 카테고리의 다른 글

[Leetcode] 344.Reverse String  (0) 2021.06.24
[Leetcode] 238. Product of Array Except Self  (0) 2021.06.23
[Leetcode] 125.Valid Palindrome  (0) 2021.06.22
[Leetcode] 121.Best tiem to Buy and Sell Stock  (0) 2021.06.21
[Leetcode] 1. Tow Sum  (0) 2021.06.16

최근댓글

최근글