LeetCode.1637
两点之间不包含任何点的最宽垂直区域
给你 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 <= 105
points[i].length == 2
0 <= xi, yi <= 109
Solution
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| #include <algorithm> #include <iostream> #include <vector>
using namespace std;
class Solution { public: int maxWidthOfVerticalArea(vector<vector<int>> &points) { sort(points.begin(), points.end(), [](vector<int> &_a, vector<int> &_b) -> bool { if (_a.front() == _b.front()) return _a.back() < _b.back(); return _a.front() < _b.front(); }); int maxWidth = 0; for (auto i = points.begin(); i < points.end() - 1; ++i) { maxWidth = max((*next(i)).front() - (*i).front(), maxWidth); } return maxWidth; } };
int main() { vector<vector<int>> points = {{3, 1}, {9, 0}, {1, 0}, {1, 4}, {5, 3}, {8, 8}}; Solution sol; int maxWidth = sol.maxWidthOfVerticalArea(points); cout << "Maximum Width of Vertical Area: " << maxWidth << endl; return 0; }
|
Summary
- Make fallbacks for sort()
- Familiar with iterator
- Lambda function