Timeline
Timeline
2025-11-26
init
Math
Problem:
Brute force enumeration, note comparing two floating-point numberswhen comparing a and b, use fabs(a-b) <= EPSto determine if they are equal
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061 | 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; // Enumerate pairs of points to get 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]) { // Vertical line is_vertical = true; k = DBL_MAX; b = points[i][0]; // x = b } else { // Non-vertical line 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; // Traverse each line and count the number of points 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; }}; |
