149. Max Points on a Line(直线上最多的点数)
题目大意
Given an array of points where points[i] = [xi, yi]
represents a point on the X-Y plane, return the maximum number of points that lie on the same straight line.
中文释义
给定一个点数组,其中 points[i] = [xi, yi]
表示 X-Y 平面上的一个点,返回在同一直线上的最大点数。
示例
-
示例 1:
- 输入:
points = [[1,1],[2,2],[3,3]]
- 输出:
3
- 输入:
-
示例 2:
- 输入:
points = [[1,1],[3,2],[5,3],[4,1],[2,3],[1,4]]
- 输出:
4
- 输入:
限制条件
1 <= points.length <= 300
points[i].length == 2
-10^4 <= xi, yi <= 10^4
- 所有点都是唯一的。
解题思路
使用哈希表来存储每个点与其他点形成的斜率。计算每个点与其他点的斜率,并将斜率的计数存储在哈希表中,以找出最多点在同一直线上的数量。
步骤说明
- 遍历每个点,为每个点建立一个斜率的哈希表。
- 对于每个点,计算它与其他点的斜率。
- 如果两点重合,增加重合点的计数。
- 否则,计算两点间的斜率,并在哈希表中更新该斜率的计数。
- 对每个点,找出斜率哈希表中的最大计数并加上重合点的计数,以确定最多点在同一直线上的数量。
- 更新并返回最大值。
代码
class Solution {
public:
int GCD(int a, int b) {
return b == 0 ? a : GCD(b, a % b);
}
int maxPoints(vector<vector<int>>& points) {
int n = points.size(), max_points = 0;
if (n <= 2) return n;
for (int i = 0; i < n; i++) {
unordered_map<string, int> slope_map;
int dup = 1;
for (int j = 0; j < n; j++) {
if (i == j) continue;
int dx = points[i][0] - points[j][0];
int dy = points[i][1] - points[j][1];
if (dx == 0 && dy == 0) {
dup++;
continue;
}
int gcd = GCD(dx, dy);
slope_map[to_string(dy / gcd) + "/" + to_string(dx / gcd)]++;
}
max_points = max(max_points, dup);
for (auto &[k, v] : slope_map) {
max_points = max(max_points, v + dup);
}
}
return max_points;
}
};