---
# System prepended metadata

title: 1762. Buildings With an Ocean View
tags: [Leetcode, FaceBook, Medium, Stack]

---

# 1762. Buildings With an Ocean View
###### tags: `Leetcode` `Medium` `FaceBook` `Stack`
Link: https://leetcode.com/problems/buildings-with-an-ocean-view/
## Code
### 思路一 
```java=
class Solution {
    public int[] findBuildings(int[] heights) {
        List<Integer> ans = new ArrayList<>();
        int rightMax = 0;
        
        for(int i = heights.length-1; i>=0; i--){
            if(heights[i]>rightMax){
                rightMax = heights[i];
                ans.add(i);
            }
        }
        Collections.reverse(ans);
        int[] res = new int[ans.size()];
        for(int i = 0;i < ans.size();i++){
            res[i] = ans.get(i);
        }
        return res;
    }
}
```
### 思路二 单调栈
```java=
class Solution {
    public int[] findBuildings(int[] heights) {
        Stack<Integer> s = new Stack<>();
        for(int i = heights.length-1;i >= 0;i--){
            if(s.empty()) s.push(i);
            else{
                if(heights[i]>heights[s.peek()]){
                    s.push(i);
                }
            }
        }
        int[] res = new int[s.size()];
        int idx = 0;
        while(!s.empty()){
            res[idx++] = s.pop();
        }
        return res;
    }
}
```