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]
相关推荐
fpcc28 分钟前
数据结构和算法—数学的应用
数据结构·c++·算法
皓月斯语31 分钟前
B4451 [GESP202512 四级] 建造 题解
数据结构·c++·算法·题解
z小猫不吃鱼1 小时前
模型剪枝经典论文精读:DepGraph: Towards Any Structural Pruning
算法·机器学习·剪枝
Ulyanov2 小时前
Python实现6-DOF刚体仿真器(下)——环境扰动与控制闭环
开发语言·python·算法·系统仿真·雷达电子对抗·导引头
牧以南歌〆2 小时前
数据结构<八>链式队列
c语言·数据结构·算法
Reart2 小时前
Leetcode 188.买卖股票的最佳时机4(718)
后端·算法
2601_950760792 小时前
BCMA:急性髓系白血病免疫治疗的新型可行靶点
人工智能·算法·蛋白
Reart3 小时前
Leetcode 123.买卖股票的最佳时期3(内有随心谈,718)
后端·算法
可编程芯片开发3 小时前
基于RMDCFT算法的天基雷达空间机动目标检测方法MATLAB仿真,对比FRFT和DFT算法
算法
noipp4 小时前
推荐题目:洛谷 B2099 矩阵交换行
线性代数·算法·矩阵