1637. Widest Vertical Area Between Two Points Containing No Points

给定平面上n个点,找到最宽的垂直区域,该区域没有点。思路是对点按x坐标排序,然后计算相邻点的x坐标差的最大值作为宽度。
摘要由CSDN通过智能技术生成

刷题笔记

1637. Widest Vertical Area Between Two Points Containing No Points

题目

Given n points on a 2D plane where points[i] = [xi, yi], Return the widest vertical area between two points such that no points are inside the area.

A vertical area is an area of fixed-width extending infinitely along the y-axis (i.e., infinite height). The widest vertical area is the one with the maximum width.

Note that points on the edge of a vertical area are not considered included in the area.
在这里插入图片描述

思路

  1. 首先想到竖向间隔取决于横坐标,则要对横坐标进行操作。
  2. 按照横坐标对点进行sort。
  3. 对两个横坐标之间的间隔值进行类似于一轮差值选择排序的选取最大值并返回

代码实现

class Solution {
    public int maxWidthOfVerticalArea(int[][] points) {
        int[] x = new int[points.length];
        for (int i = 0; i < points.length; i++) {
            x[i] = points[i][0];
        }
        Arrays.sort(x);
        int width = 0;
        for (int j = 0; j < x.length - 1; j++) {
            if ((x[j + 1] - x[j]) > width) {
                width = x[j + 1] - x[j];
            }
        }
        return width;
    }
}

以上代码是博主第一个自行完成并一次accept的题,菜鸡的第一次TAT
下面看看评论大神的精炼代码

 public int maxWidthOfVerticalArea(int[][] points) {
        Arrays.sort(points, Comparator.comparingInt(p -> p[0]));
        int mx = 0;
        for (int i = 1; i < points.length; ++i) {
            mx = Math.max(mx, points[i][0] - points[i - 1][0]);
        }
        return mx;
    }

在评论里看到很多人用Math.max()来比较大小,直接代替了if语句先判断再赋值的过程,简洁很多。
Arrays.sort()里对比较器的设置是我第一次看到,不得不承认这个是知识盲区了,还需要再理解一下。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值