Leetcode 1762. Buildings With an Ocean View [Python]

考查stack。stack顶的元素一定要比待入stack的元素大,否则弹出stack顶元素。

class Solution:
    def findBuildings(self, heights: List[int]) -> List[int]:
        stack = []
        for index, B in enumerate(heights):
            if not stack or stack[-1][1] > B:
                stack.append((index, B))
            else: 
                while stack and stack[-1][1] <= B:
                    stack.pop(-1)
                stack.append((index, B))
        res = []
        for index, B in stack:
            res.append(index)
        return res

你可能感兴趣的:(Leetcode学习记录,leetcode,python,算法)