KK's blog

每天积累多一些

0%

LeetCode 1762 Buildings With an Ocean View

LeetCode



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<sup>5</sup> 1 <= heights[i] <= 10<sup>9</sup>

题目大意:

大海在右边,求看到大海的大厦的下标

解题思路:

数组元素之间大小关系且保持顺序,用stack

解题步骤:

N/A

注意事项:

Python代码:

1
2
3
4
5
6
7
def findBuildings(self, heights: List[int]) -> List[int]:
stack = []
for i in range(len(heights)):
while stack and heights[i] >= heights[stack[-1]]:
stack.pop()
stack.append(i) # 4 3 1
return stack

算法分析:

时间复杂度为O(n),空间复杂度O(n)


算法II解题思路(推荐):

数组元素之间大小关系且保持顺序,用stack

解题步骤:

类似于Leetcode 42的trapping rain water,看不到大海表示在低位。此题只求单边,从右往左扫描一次。

注意事项:

Python代码:

1
2
3
4
5
6
7
def findBuildings2(self, heights: List[int]) -> List[int]:
right_max, res = 0, []
for i in reversed(range(len(heights))):
if heights[i] > right_max:
res.append(i)
right_max = max(right_max, heights[i])
return res[::-1]

算法分析:

时间复杂度为O(n),空间复杂度O(1)

Free mock interview