时间轴

2025-11-26

init


题目:

暴力枚举,注意比较两个浮点数a,b时用fabs(a-b)<= EPS来判断是否相等

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
51
52
53
54
55
56
57
58
59
60
61
#include <cfloat>
#include <cmath>
#include <vector>
using std::vector;

struct Line {
double k;
double b;
bool is_vertical;
};

class Solution {
public:
int maxPoints(vector<vector<int>>& points) {
int n = points.size();
if (n == 0) return 0;
if (n == 1) return 1;

const double EPS = 1e-9;
vector<Line> lines;

// 枚举两两点得到直线
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
double k, b;
bool is_vertical;
if (points[i][0] == points[j][0]) {
// 垂直线
is_vertical = true;
k = DBL_MAX;
b = points[i][0]; // x = b
} else {
// 非垂直线
is_vertical = false;
k = (double)(points[j][1] - points[i][1]) / (points[j][0] - points[i][0]);
b = points[j][1] - k * points[j][0]; // y = kx + b
}
lines.push_back({k, b, is_vertical});
}
}

int max_count = 0;

// 遍历每条直线,统计点数
for (const Line& line : lines) {
int cnt = 0;
for (const auto& point : points) {
int x = point[0], y = point[1];
if (line.is_vertical) {
if (fabs(x - line.b) < EPS) cnt++;
} else {
if (fabs(y - (line.k * x + line.b)) < EPS) cnt++;
}
}
if (cnt > max_count) max_count = cnt;
}

return max_count;
}
};