March 19, 2022

1762. Buildings With an Ocean View

1762. Buildings With an Ocean View

Traverse from right to left. Time = O(n), space = O(n)

class Solution {
    public int[] findBuildings(int[] heights) {
        int curMax = heights[heights.length - 1];
        List<Integer> buildings = new ArrayList<>();
        buildings.add(0, heights.length - 1);
        for (int i = heights.length - 2; i >= 0; i--) {
            if (heights[i] > curMax) {
                buildings.add(i);
                curMax = heights[i];
            }            
        }
        int[] res = new int[buildings.size()];
        for(int i = 0; i < res.length; i++) {
            res[i] = buildings.get(res.length - 1 - i);
        }
        return res;
    }
}
comments powered by Disqus