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]
相关推荐
狮子也疯狂8 小时前
基于Django实现的智慧校园考试系统-自动组卷算法实现
python·算法·django
爱coding的橙子8 小时前
每日算法刷题Day84:11.11:leetcode 动态规划9道题,用时2h
算法·leetcode·动态规划
shenghaide_jiahu9 小时前
字符串匹配和回文串类题目
学习·算法·动态规划
有意义9 小时前
为什么说数组是 JavaScript 开发者必须精通的数据结构?
前端·数据结构·算法
努力努力再努力wz9 小时前
【Linux进阶系列】:线程(下)
linux·运维·服务器·c语言·数据结构·c++·算法
rit84324999 小时前
瑞利信道下PSK水声通信系统均衡技术
算法
ValhallaCoder9 小时前
Day33-动态规划
数据结构·python·算法·动态规划
不穿格子的程序员10 小时前
从零开始刷算法-二分-搜索插入位置
算法·二分查找
代码程序猿RIP10 小时前
【C 语言面试】高频考点深度解析
java·面试·职场和发展
zhugby10 小时前
受限长度路径搜索算法
经验分享·算法·启发式算法·哈密顿问题·路径搜索算法