GuilinDev

Lc1762

05 August 2008

1762 Buildings With an Ocean View

一维数组,每个元素代表房子的高度,海景在右边,求所有能看到海的房子的indices

从右到左遍历,维护一个最高度

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
    public int[] findBuildings(int[] heights) {
        List<Integer> ls = new ArrayList<>();
        int last = Integer.MIN_VALUE;
        for (int i = heights.length - 1; i >= 0; i--) {
            if (heights[i] > last) {
                ls.add(i);
                last = heights[i];
            }
        }
        
        int index = 0;
        int[] res = new int[ls.size()];
        for (int i = ls.size() - 1; i >= 0; i--)
            res[index++] = ls.get(i);
        
        return res;
    }
}