LeetCode: 149. Max Points on a Line
LeetCode: 149. Max Points on a Line
题目描述
Given n
points on a 2D plane, find the maximum number of points that lie on the same straight line.
Example 1:
Input: [[1,1],[2,2],[3,3]]
Output: 3
Explanation:
^
|
| o
| o
| o
+------------->
0 1 2 3 4
Example 2:
Input: [[1,1],[3,2],[5,3],[4,1],[2,3],[1,4]]
Output: 4
Explanation:
^
|
| o
| o o
| o
| o o
+------------------->
0 1 2 3 4 5 6
解题思路
用 map
统计所有直线上的 点的个数
AC 代码
/** * Definition for a point. * struct Point { * int x; * int y; * Point() : x(0), y(0) {} * Point(int a, int b) : x(a), y(b) {} * }; */
class Solution {
// 用 Ax + By + C = 0 的形式表示点 pt1 和点 pt2 构成的直线
// 返回值是三元组 <A, B, C>
tuple<int, int, int> MakeLine(Point pt1, Point pt2)
{
int A = 0, B = 0, C = 0;
// x = b 类型
if(pt1.x == pt2.x)
{
A = 1;
B = 0;
C = -pt1.x;
}
else if(pt1.y == pt2.y)
{
A = 0;
B = 1;
C = -pt2.y;
}
else // 否则是 y = kx + b 类型
{
// 两点式直线方程:(x-x1)/(x2-x1) = (y-y1)/(y2-y1)
// 即 (y2-y1)x -(x2-x1)y -(y2-y1)x1+(x2-x1)y1 = 0
// A = y2-y1; B = -(x2-x1); C = -(y2-y1)x1+(x2-x1)y1
A = pt2.y - pt1.y;
B = -(pt2.x - pt1.x);
C = -(pt2.y - pt1.y)*pt1.x + (pt2.x - pt1.x)*pt1.y;
}
return {A, B, C};
}
// 判断点 pt 是否在直线 line 上
bool PtOnLine(Point pt, const tuple<int, int, int>& line)
{
int A = get<0>(line);
int B = get<1>(line);
int C = get<2>(line);
return ((long long)A*pt.x+B*pt.y+C == 0);
}
public:
int maxPoints(vector<Point>& points) {
if(points.empty()) return 0;
// 统计线上的点数
map<tuple<int, int, int>, int> pointsInLine;
for(size_t i = 0; i < points.size(); ++i)
{
for(size_t j = i+1; j < points.size(); ++j)
{
auto line = MakeLine(points[i], points[j]);
if(pointsInLine.find(line) == pointsInLine.end()) pointsInLine[line] = 0;
}
}
int maxCnt = 1;
// 统计
for(size_t i = 0; i < points.size(); ++i)
{
for(auto& line : pointsInLine)
{
if(PtOnLine(points[i], line.first) == true)
{
if(++pointsInLine[line.first] > maxCnt)
{
maxCnt = pointsInLine[line.first] ;
}
}
}
}
return maxCnt;
}
};