首页 > 编程语言 >59天【代码随想录算法训练营34期】第十章 单调栈part02( ● 503.下一个更大元素II ● 42. 接雨水 )

59天【代码随想录算法训练营34期】第十章 单调栈part02( ● 503.下一个更大元素II ● 42. 接雨水 )

时间:2024-05-29 16:47:21浏览次数:22  
标签:59 nums int part02 随想录 len height stack append

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

标签:59,nums,int,part02,随想录,len,height,stack,append
From: https://www.cnblogs.com/miramira/p/18220596

相关文章