classSolution { public: intmaxPoints(vector<vector<int>>& points){ int n = points.size(); if (n == 0) return0; if (n == 1) return1;
constdouble 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 (constauto& 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; }