题目:
给出二维平面上的n个点,求最多有多少点在同一条直线上。
样例:
给出4个点:(1, 2), (3, 6), (0, 0), (1, 3)。
一条直线上的点最多有3个。思路:
选定一个点,分别计算其他点和它构成的直线的斜率,斜率相同的点肯定在同一条直线上。
注意:1.在计算机里使用double表示斜率,是不严谨的也是不正确的,double有精度误差,double是有限的,斜率是无限的;表示斜率最靠谱的方式是用最简分数,即分子分母都无法再约分了。分子分母同时除以他们的最大公约数gcd即可得到最简分数。2.注意重合点3.注意斜率无穷大的,$tan=(y_1-y_2)/(x_1-x_2)$$,所以用一个pair存储分子分母就好了。
参考答案:
/** * 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: /* * @param points: an array of point * @return: An integer */ int maxPoints(vector&points) { // write your code here int res = 0; for(int i=0; i , int> m; int common = 1;//记录相同点的个数 for(int j = i+1; j ,int>::iterator it; for(it = m.begin(); it != m.end(); it++){ res = max(res, it->second+common); } } return res; } int gcd(int a, int b){//a,b最大公约数 return (b==0) ? a : gcd(b, a%b); }};