给定二维平面上有 n 个点,求最多有多少点在同一条直线上。
详见:https://leetcode.com/problems/max-points-on-a-line/description/
/** * Definition for a point. * struct Point { * int x; * int y; * Point() : x(0), y(0) {} * Point(int a, int b) : x(a), y(b) {} * }; */ class Solution { public: int maxPoints(vector<Point>& points) { int res = 0; for (int i = 0; i < points.size(); ++i) { map<pair<int, int>, int> m; int duplicate = 1; for (int j = i + 1; j < points.size(); ++j) { if (points[i].x == points[j].x && points[i].y == points[j].y) { ++duplicate; continue; } int dx = points[j].x - points[i].x; int dy = points[j].y - points[i].y; int d = gcd(dx, dy); ++m[{dx / d, dy / d}]; } res = max(res, duplicate); for (auto it = m.begin(); it != m.end(); ++it) { res = max(res, it->second + duplicate); } } return res; } int gcd(int a, int b) { return (b == 0) ? a : gcd(b, a % b); } };
参考:https://www.cnblogs.com/grandyang/p/4579693.html
原文地址:https://www.cnblogs.com/xidian2014/p/8727564.html
时间: 2024-10-12 04:27:42