0%

149. 直线上最多的点数

149. 直线上最多的点数

暴力 枚举斜率
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
public:
int maxPoints(vector<vector<int>>& points) {
int sz = points.size();
int ret = 1;
for(int i = 0; i < sz; ++i)
{
unordered_map<double, int> map;
for(int j = 0; j < sz; ++j)
{
if(j == i)
continue;
double grad = (points[i][1] - points[j][1]) * 1.0/ (points[i][0] - points[j][0]); // 浮点除以0是不确定行为,不应该保留
++map[grad];
ret = max(map[grad] + 1, ret);
}
}
return ret;
}
};
直接参考答案
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
class Solution {
public:
int maxPoints(vector<vector<int>>& points) {
int sz = points.size();
if(sz <= 2)
return sz;
int ret = 0;
for(int i = 0; i < sz; ++i)
{
// 优化方案
// 剩下的点都不如ret多了,那接下来不管怎么弄都超不过ret了,所以没用了意义
if(ret > sz - i || ret > sz / 2)
break;
// 答案中的数字太抽象,这里将二元组用string表示
unordered_map<string, int> map;
for(int j = i + 1; j < sz; ++j)
{
int x = points[j][0] - points[i][0];
int y = points[j][1] - points[i][1];
if(x == 0)
y = 1;
else if(y == 0)
x = 1;
else
{
if(y < 0)
{
x = -x;
y = -y;
}
int gcdXY = gcd(abs(x), abs(y));
x /= gcdXY;
y /= gcdXY;
}
++map[to_string(x) + ":" + to_string(y)];
}
int maxN = 0;
for(auto& [_, num] : map)
maxN = max(maxN, num + 1);
ret = max(ret, maxN);
}
return ret;
}
private:
// 欧几里得算法求公约数
int gcd(int a, int b)
{
return b ? gcd(b, a % b) : a;
}
};