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.

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 <= 105
  • 1 <= heights[i] <= 109
java 复制代码
public class Solution {
    public int[] findBuildings(int[] heights) {
        ArrayList<Integer> results = new ArrayList<Integer>();

        if (heights == null || heights.length == 0) {
            return new int[0]; // Return an empty array if input is null or empty
        }

        int highest_building = -1;

        for (int i = heights.length - 1; i >= 0; i--) {
            if (heights[i] > highest_building) {
                highest_building = heights[i];
                results.add(i); // 从右往左遍历,把最高的楼房存下来
            }
        }

        // Convert the ArrayList<Integer> to int[] 这里要特别注意,Interger的arraylist到int的array要手动转换一下。
        int[] resultArray = new int[results.size()];
        int j = 0;
        for (int i = results.size() - 1; i >=0; i--) {
            resultArray[j] = results.get(i);
            j++;
        }

        return resultArray;
    }
}
相关推荐
yi0112 小时前
LeetCode 219:存在重复元素 II——哈希表记录“最近一次出现的位置”
数据结构·人工智能·笔记·python·算法·leetcode·哈希表
灯澜忆梦5 小时前
【面向对象编程C++】| 基础语法
java·c++·算法
小蒋观天下5 小时前
专项方案:大场景港口AI安防、多干扰环境下的算法调优与落地实操
人工智能·深度学习·算法·安全·机器学习·计算机视觉·ai大模型
Evand J5 小时前
【电机滤波例程5】渐消因子自适应扩展卡尔曼滤波(EKF),MATLAB。PMSM负载突变下的状态估计。附下载链接
算法·matlab
H.莓飛5 小时前
【数据结构】二叉树_OJ题
linux·开发语言·数据结构·算法
好想像大佬一样能够ak所有6 小时前
Leetcode35.搜索插入位置
数据结构·算法·leetcode
aqiu1111116 小时前
【C++算法打怪专栏】LeetCode 165. 比较版本号(双指针与字符串流法)
c++·算法·leetcode
黄金龙PLUS6 小时前
如何基于置换算法来设计对称加密算法
算法·网络安全·密码学·哈希算法·同态加密
不会就选b6 小时前
算法日常・每日刷题--<动态规划>14
算法
赛博守夜人6 小时前
跨境业务与出海合规之九:海外买量投放与营销虚假流量(Ad Fraud):跨国机房群控与归因欺诈识别算法
算法·安全