题目链接:https://leetcode-cn.com/problems/max-points-on-a-line/
题意
给定平面上的n个点,求最多点共线的点数
题解
对于两个点构成的直线可以用方向向量gcd表示以避免斜率误差,枚举两点形成直线,然后枚举所有其它点判断可以解,复杂度
O
(
n
3
)
O(n^3)
O(n3)
也可以枚举一个点,然后求该点到所有点的方向向量然后map保存来求最大数目的相同向量,时间可以压缩到
O
(
n
2
)
/
O
(
n
2
l
o
g
n
)
O(n^2)/O(n^2logn)
O(n2)/O(n2logn)
code
int gcd(int x, int y)
{
return y == 0 ? x : gcd(y, x % y);
}
const int N = 100001;
int n;
int x[N], y[N];
map<pair<int, int>, int> cnt;
class Solution
{
public:
int maxPoints(vector<vector<int>> &points)
{
n = points.size();
for (int i = 1; i <= n; i++)
{
x[i] = points[i - 1][0];
y[i] = points[i - 1][1];
}
if (n < 3)
{
return n;
}
int fl = 0;
int mp = 0;
for (int i = 1; i <= n; i++)
{
cnt.clear();
for (int j = 1; j <= n; j++)
{
if (i == j)
continue;
int dx = x[j] - x[i];
int dy = y[j] - y[i];
if (dx < 0)
{
dx = -dx;
dy = -dy;
}
if (dx == 0)
dy = 1;
if (dy == 0)
dx = 1;
if (dx && dy)
{
int g = gcd(abs(dx), abs(dy));
dx /= g;
dy /= g;
}
pair<int, int> p = make_pair(dx, dy);
int tmp = ++cnt[p];
mp = max(mp, tmp);
}
}
return mp + 1 + fl;
}
};