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]
相关推荐
yyy(十一月限定版)几秒前
算法——模拟
算法
DeepVis Research3 分钟前
【Chaos/Neuro】2026年度混沌动力学仿真与机器遗忘算法基准索引 (Benchmark Index)
人工智能·算法·数据集·混沌工程·高性能计算
一起养小猫17 分钟前
LeetCode100天Day9-无重复字符的最长子串与赎金信
java·开发语言·数据结构·leetcode
white-persist22 分钟前
【内网运维】Netstat与Wireshark:内网运维溯源实战解析
运维·网络·数据结构·测试工具·算法·网络安全·wireshark
会员果汁23 分钟前
7.设计模式-模板方法模式
算法·设计模式·模板方法模式
努力学算法的蒟蒻23 分钟前
day52(1.2)——leetcode面试经典150
算法·leetcode·面试
java修仙传26 分钟前
力扣hot100:字符串解码
算法·leetcode·职场和发展
Joe_Blue_0228 分钟前
Matlab入门案例介绍—如何创建代码
算法·matlab·matlab基础入门案例介绍
梭七y31 分钟前
【力扣hot100题】(116)矩阵置零
算法·leetcode·矩阵
应用市场36 分钟前
# 内容平台推荐算法与创作者激励机制——从抖音/B站看流量分配的技术逻辑
算法·机器学习·推荐算法