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]
相关推荐
·云扬·16 分钟前
【PmHub面试篇】Gateway全局过滤器统计接口调用耗时面试要点解析
面试·职场和发展·gateway
编程绿豆侠2 小时前
力扣HOT100之二分查找: 34. 在排序数组中查找元素的第一个和最后一个位置
数据结构·算法·leetcode
Shan12052 小时前
找到每一个单词+模拟的思路和算法
数据结构·算法
国家不保护废物3 小时前
微信红包算法深度解析:从产品思维到代码实现
javascript·算法·面试
小明同学013 小时前
[C++入门]简化的艺术---对模版的初步探索
开发语言·c++·算法
kaiaaaa4 小时前
算法训练第八天
算法
LL_xjbt4 小时前
代码随想录刷题day29
算法·leetcode·动态规划
叶子2024224 小时前
守护进程实验——autoDL
人工智能·算法·机器学习
半桔4 小时前
【算法深练】分组循环:“分”出条理,化繁为简
数据结构·c++·算法·leetcode·面试·职场和发展
天天爱吃肉82184 小时前
【十年技术演进深度解构:车载充电机(OBC)将成为新能源汽车的“能源大脑”】
python·嵌入式硬件·算法·汽车·能源