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]
相关推荐
Aspect of twilight42 分钟前
LeetCode华为2025年秋招AI大模型岗刷题(四)
算法·leetcode·职场和发展
有泽改之_8 小时前
leetcode146、OrderedDict与lru_cache
python·leetcode·链表
im_AMBER8 小时前
Leetcode 74 K 和数对的最大数目
数据结构·笔记·学习·算法·leetcode
无敌最俊朗@8 小时前
STL-vector面试剖析(面试复习4)
java·面试·职场和发展
t198751288 小时前
电力系统经典节点系统潮流计算MATLAB实现
人工智能·算法·matlab
断剑zou天涯8 小时前
【算法笔记】蓄水池算法
笔记·算法
长安er9 小时前
LeetCode 206/92/25 链表翻转问题-“盒子-标签-纸条模型”
java·数据结构·算法·leetcode·链表·链表翻转
Benmao⁢9 小时前
C语言期末复习笔记
c语言·开发语言·笔记·leetcode·面试·蓝桥杯
唯道行9 小时前
计算机图形学·23 Weiler-Athenton多边形裁剪算法
算法·计算机视觉·几何学·计算机图形学·opengl
CoderYanger9 小时前
动态规划算法-01背包问题:50.分割等和子集
java·算法·leetcode·动态规划·1024程序员节