59天【程式碼隨想錄演算法訓練營34期】第十章 單調棧part02( ● 503.下一個更大元素II ● 42. 接雨水 )

MiraMira發表於2024-05-29

503.下一個更大元素II

class Solution:
    def nextGreaterElements(self, nums: List[int]) -> List[int]:
        dp = [-1] * len(nums)
        stack = []

        for i in range(len(nums)*2):
            while(len(stack)!=0 and nums[i%len(nums)]>nums[stack[-1]]):
                dp[stack[-1]] = nums[i%len(nums)]
                stack.pop()
            stack.append(i%len(nums))
        return dp

42. 接雨水

class Solution:
    def trap(self, height: List[int]) -> int:
        stack = [0]
        result = 0
        
        for i in range(1, len(height)):
            if height[i] < height[stack[-1]]:
                stack.append(i)
            elif height[i] == height[stack[-1]]:
                stack.pop()
                stack.append(i)
            else:
                while stack and height[i] > height[stack[-1]]:
                    mid_height = height[stack[-1]]
                    stack.pop()
                    if stack:
                        left_height = height[stack[-1]]
                        right_height = height[i]
                        height_ = min(left_height, right_height) - mid_height
                        width_ = i - stack[-1] - 1
                        result += height_ * width_
                stack.append(i)
        return result

相關文章