149 Max Points on a Line 直線上最多的點數
阿新 • • 發佈:2018-04-06
ret post for cnblogs str true tor scrip des
給定二維平面上有 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
149 Max Points on a Line 直線上最多的點數