[LeetCode] Buildings With an Ocean View

1762. Buildings With an Ocean View

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public:
vector<int> findBuildings(vector<int>& heights) {
int sz = heights.size(), mx = -1;
vector<int> res;
res.reserve(sz);
for(auto i = sz - 1; i >= 0; --i) {
if (mx < heights[i]) res.push_back(i);
mx = max(mx, heights[i]);
}
reverse(begin(res), end(res));
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/12/07/PS/LeetCode/buildings-with-an-ocean-view/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.