刷题笔记
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.
思路
- 首先想到竖向间隔取决于横坐标,则要对横坐标进行操作。
- 按照横坐标对点进行sort。
- 对两个横坐标之间的间隔值进行类似于一轮差值选择排序的选取最大值并返回
代码实现
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()里对比较器的设置是我第一次看到,不得不承认这个是知识盲区了,还需要再理解一下。