代码随想录day59|503. 下一个更大元素 II42. 接雨水

503. 下一个更大元素 II

class Solution:
    def nextGreaterElements(self, nums: List[int]) -> List[int]:
        st = [0]
        result = [-1]*(len(nums)*2)
        nums = nums +nums
        for i in range(1,len(nums)):
            if nums[i] <= nums[st[-1]]:
                st.append(i)
            else:
                while st and nums[i] > nums[st[-1]]:
                    result[st[-1]] = nums[i]
                    st.pop()
                st.append(i)
        return result[:int(len(nums)/2)]

42. 接雨水

class Solution:
    def trap(self, height: List[int]) -> int:
        st = [0]
        result = 0
        for i in range(1, len(height)):
            if height[i] <= height[st[-1]]:
                st.append(i)
            else:
                while st and height[i] > height[st[-1]]:
                    mid = height[st[-1]]
                    st.pop()
                    if st:
                        h = min(height[i], height[st[-1]]) - mid
                        w = i - st[-1] - 1
                        result += h * w
                st.append(i)
        return result

你可能感兴趣的:(算法,数据结构)