Easy
题目描述
给你 n 个二维平面上的点 points ,其中 points[i] = [xi, yi] ,请你返回两点之间内部不包含任何点的 最宽垂直区域 的宽度。
垂直区域 的定义是固定宽度,而 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
- 2 <= n <= 10^5
- points[i].length == 2
- 0 <= xi, yi <= 10^9
思考提示:
- 尝试对点进行排序
- 思考一个点的 y 坐标是否相关
解题思路
这道题的关键洞察是:垂直区域的宽度只与 x 坐标相关,y 坐标完全不重要。
解题思路:
理解题意:我们需要找到两个垂直线之间的最大距离,使得这个区域内部没有任何点。由于垂直区域在 y 轴上无限延伸,所以 y 坐标不影响结果。
转化问题:问题转化为在 x 轴上找到相邻两个不同 x 坐标之间的最大差值。
算法步骤:
- 提取所有点的 x 坐标
- 对 x 坐标进行排序并去重(相同 x 坐标的点不会影响垂直区域的划分)
- 计算相邻 x 坐标之间的最大差值
优化考虑:
- 可以直接对原数组按 x 坐标排序,然后遍历相邻点计算最大 x 坐标差值
- 不需要显式去重,因为即使有相同 x 坐标的相邻点,它们的差值为 0,不会影响最大值
时间复杂度:O(n log n),主要是排序的时间复杂度 空间复杂度:O(1),如果不考虑排序的额外空间;O(n) 如果考虑排序空间
代码实现
class Solution {
public:
int maxWidthOfVerticalArea(vector<vector<int>>& points) {
sort(points.begin(), points.end());
int maxWidth = 0;
for (int i = 1; i < points.size(); i++) {
maxWidth = max(maxWidth, points[i][0] - points[i-1][0]);
}
return maxWidth;
}
};
class Solution:
def maxWidthOfVerticalArea(self, points: List[List[int]]) -> int:
points.sort()
max_width = 0
for i in range(1, len(points)):
max_width = max(max_width, points[i][0] - points[i-1][0])
return max_width
public class Solution {
public int MaxWidthOfVerticalArea(int[][] points) {
Array.Sort(points, (a, b) => a[0].CompareTo(b[0]));
int maxWidth = 0;
for (int i = 1; i < points.Length; i++) {
maxWidth = Math.Max(maxWidth, points[i][0] - points[i-1][0]);
}
return maxWidth;
}
}
var maxWidthOfVerticalArea = function(points) {
points.sort((a, b) => a[0] - b[0]);
let maxWidth = 0;
for (let i = 1; i < points.length; i++) {
maxWidth = Math.max(maxWidth, points[i][0] - points[i-1][0]);
}
return maxWidth;
};
复杂度分析
| 复杂度类型 | 值 | 说明 |
|---|---|---|
| 时间复杂度 | O(n log n) | 排序操作的时间复杂度 |
| 空间复杂度 | O(1) | 原地排序,不考虑排序算法的额外空间 |
相关题目
. Maximum Gap (Medium)
. Maximum Consecutive Floors Without Special Floors (Medium)