考察的知识点:哈希;
解答方法分析:
- 如果给定的点数量小于等于2,直接返回点的数量作为结果,因为任意两个点都能构成一条直线。
- 对于点集中的每个点,计算它和其他点之间的斜率,斜率可以用两点之间的纵坐标差与横坐标差的比值表示。
- 为了方便计算,使用哈希表
slopeCount
来记录每个斜率对应的点的数量。同时,使用一个变量samePoints
来记录与当前点坐标相同的点的数量。 - 遍历每个点后,在哈希表
slopeCount
中找到点数最多的斜率对应的数量,将其加上samePoints
得到在同一条直线上最多的点的数量。 - 保存最大的点数作为结果,返回结果。
所用编程语言:C++;
完整编程代码:↓
class Solution { public: int maxPoints(vector<vector<int>>& points) { int n = points.size(); if (n <= 2) { return n; } int res = 0; for (int i = 0; i < n; i++) { unordered_map<string, int> slopeCount; int samePoints = 1; for (int j = i + 1; j < n; j++) { if (points[i][0] == points[j][0] && points[i][1] == points[j][1]) { samePoints++; continue; } string slope = calculateSlope(points[i], points[j]); slopeCount[slope]++; } int maxPointsOnLine = samePoints; for (auto it = slopeCount.begin(); it != slopeCount.end(); ++it) { maxPointsOnLine = max(maxPointsOnLine, it->second + samePoints); } res = max(res, maxPointsOnLine); } return res; } private: string calculateSlope(const vector<int>& point1, const vector<int>& point2) { if (point1[0] == point2[0]) { return "inf"; } else { return to_string((double)(point2[1] - point1[1]) / (point2[0] - point1[0])); } } };