持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第2天,点击查看活动详情
1637. 两点之间不包含任何点的最宽垂直面积:
给你 n 个二维平面上的点 points ,其中 ,请你返回两点之间内部不包含任何点的 最宽垂直面积 的宽度。
垂直面积 的定义是固定宽度,而 y 轴上无限延伸的一块区域(也就是高度为无穷大)。 最宽垂直面积 为宽度最大的一个垂直面积。
请注意,垂直区域 边上 的点 不在 区域内。
样例 1:
输入:
points = [[8,7],[9,9],[7,4],[9,7]]
输出:
1
解释:
红色区域和蓝色区域都是最优区域。
样例 2:
输入:
points = [[3,1],[9,0],[1,0],[1,4],[5,3],[8,8]]
输出:
3
提示:
- n == points.length
- points[i].length == 2
分析
- 面对这道算法题目,二当家的陷入了沉思。
- 根据题意要求,两点之间区域内不能有其他点,但是边上的点不算在区域内,所以在x轴相同的情况下,y轴可以不同,并且最终要算宽度,那高度就没什么用。
- 按照x轴坐标排序,仅仅计算邻近点的最大距离即可。
题解
rust
impl Solution {
pub fn max_width_of_vertical_area(mut points: Vec<Vec<i32>>) -> i32 {
points.sort_unstable_by_key(|p| p[0]);
let mut ans = 0;
(1..points.len()).for_each(|i| {
ans = ans.max(points[i][0] - points[i - 1][0]);
});
ans
}
}
go
func maxWidthOfVerticalArea(points [][]int) int {
sort.Slice(points, func(i, j int) bool { return points[i][0] < points[j][0] })
ans := 0
for i := 1; i < len(points); i++ {
w := points[i][0] - points[i-1][0]
if w > ans {
ans = w
}
}
return ans
}
typescript
function maxWidthOfVerticalArea(points: number[][]): number {
points.sort((a, b) => a[0] - b[0]);
let ans = 0;
for (let i = 1; i < points.length; ++i) {
ans = Math.max(ans, points[i][0] - points[i - 1][0]);
}
return ans;
};
c
int compare(const void *a, const void *b) {
return (*(int **) a)[0] - (*(int **) b)[0];
}
int maxWidthOfVerticalArea(int** points, int pointsSize, int* pointsColSize){
qsort(points, pointsSize, sizeof(int *), compare);
int ans = 0;
for (int i = 1; i < pointsSize; ++i) {
ans = fmax(ans, points[i][0] - points[i - 1][0]);
}
return ans;
}
c++
class Solution {
public:
int maxWidthOfVerticalArea(vector<vector<int>>& points) {
sort(points.begin(), points.end(), [&](vector<int> &a, vector<int> &b) {
return a[0] < b[0];
});
int ans = 0;
for (int i = 1; i < points.size(); i++) {
ans = max(ans, points[i][0] - points[i - 1][0]);
}
return ans;
}
};
python
class Solution:
def maxWidthOfVerticalArea(self, points: List[List[int]]) -> int:
points.sort(key=lambda p: p[0])
return max(b[0] - a[0] for a, b in pairwise(points))
java
class Solution {
public int maxWidthOfVerticalArea(int[][] points) {
Arrays.sort(points, Comparator.comparingInt(a -> a[0]));
int ans = 0;
for (int i = 1; i < points.length; ++i) {
ans = Math.max(ans, points[i][0] - points[i - 1][0]);
}
return ans;
}
}
原题传送门:https://leetcode.cn/problems/widest-vertical-area-between-two-points-containing-no-points/
非常感谢你阅读本文~
放弃不难,但坚持一定很酷~
希望我们大家都能每天进步一点点~
本文由 二当家的白帽子:https://juejin.cn/user/2771185768884824/posts 博客原创~