给定一个二维平面,平面上有 n 个点,求最多有多少个点在同一条直线上。
示例 1:
输入: [[1,1],[2,2],[3,3]]
输出: 3
解释:
^
|
| o
| o
| o
+------------->
0 1 2 3 4
示例 2:
输入: [[1,1],[3,2],[5,3],[4,1],[2,3],[1,4]]
输出: 4
解释:
^
|
| o
| o o
| o
| o o
+------------------->
0 1 2 3 4 5 6
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/max-points-on-a-line
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
class Solution { public: int maxPoints(vector<vector<int>>& points) { int res = 0; for (int i = 0; i < points.size(); i++) { map<pair<int, int>, int> m; int duplicate = 1;//duplicate points for (int j = i + 1; j < points.size(); ++j) { if (points[i][0] == points[j][0] && points[i][1] == points[j][1]) { duplicate++; continue; } int dx = points[j][0] - points[i][0]; int dy = points[j][1] - points[i][1]; 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); } };