leetcode - 1762. Buildings With an Ocean View

Description

There are n buildings in a line. You are given an integer array heights of size n that represents the heights of the buildings in the line.

The ocean is to the right of the buildings. A building has an ocean view if the building can see the ocean without obstructions. Formally, a building has an ocean view if all the buildings to its right have a smaller height.

Return a list of indices (0-indexed) of buildings that have an ocean view, sorted in increasing order.

Example 1:

复制代码
Input: heights = [4,2,3,1]
Output: [0,2,3]
Explanation: Building 1 (0-indexed) does not have an ocean view because building 2 is taller.

Example 2:

复制代码
Input: heights = [4,3,2,1]
Output: [0,1,2,3]
Explanation: All the buildings have an ocean view.

Example 3:

复制代码
Input: heights = [1,3,2,4]
Output: [3]
Explanation: Only building 3 has an ocean view.

Constraints:

复制代码
1 <= heights.length <= 10^5
1 <= heights[i] <= 10^9

Solution

Iterate from right to left, only push those taller than top element into the stack.

Time complexity: o ( n ) o(n) o(n)

Space complexity: o ( n ) o(n) o(n)

Code

python3 复制代码
class Solution:
    def findBuildings(self, heights: List[int]) -> List[int]:
        stack = []
        for i in range(len(heights) - 1, -1, -1):
            if not stack or heights[stack[-1]] < heights[i]:
                stack.append(i)
        return stack[::-1]
相关推荐
熬了夜的程序员2 小时前
【LeetCode】91. 解码方法
算法·leetcode·链表·职场和发展·排序算法
大数据张老师2 小时前
数据结构——内部排序算法的选择和应用
数据结构·算法·排序算法
JohnYan3 小时前
微软验证器-验证ID功能初体验
后端·算法·安全
路弥行至3 小时前
C语言入门教程 | 第七讲:函数和程序结构完全指南
c语言·经验分享·笔记·其他·算法·课程设计·入门教程
Xの哲學3 小时前
Linux ioctl 深度剖析:从原理到实践
linux·网络·算法·架构·边缘计算
隐语SecretFlow3 小时前
隐语SecreFlow:如何全面提升MPC多方安全学习的性能?
算法
王国强20094 小时前
什么是算法复杂度?
算法
夏鹏今天学习了吗4 小时前
【LeetCode热题100(54/100)】全排列
算法·leetcode·深度优先
緈福的街口4 小时前
gps的定位图,在车的位置去寻找周围20x20的区域,怎么确定周围有多少辆车,使用什么数据结构
数据结构·算法
江塘4 小时前
机器学习-KNN算法实战及模型评估可视化(C++/Python实现)
开发语言·c++·人工智能·python·算法·机器学习