Cover image for 面试经典150题 P149 直线上最多的点数

面试经典150题 P149 直线上最多的点数


时间轴

时间轴

2025-11-26

init

数学

题目:

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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
#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;    }};
评论加载中…