给出二维平面上的n个点,求最多有多少点在同一条直线上。
样例
样例 1:
输入:(1,2),(3,6),(0,0),(1,3).
输出:3
样例 2:
输入:(1,2),(2,3),(3,2).
输出:2
注意事项
x点和y点的坐标值在-1000~1000之间
思路:
原理:经过同一点,斜率相同则在同一直线上
1、利用map记录每一个点斜率出现次数
2、注意两点相同的情况下要重复计点
3、当两点横坐标相同,无斜率情况要注意处理
/**
* 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<Point> &points) {
// write your code here
map<double,int> rates;
int len=points.size();
int res=0;
for (int i = 0; i < len; i++) {
/* code */
rates.clear();
rates[(double)INT_MAX]=1;
int same=0;
for (int j = i+1; j < len; j++) {
/* code */
if(points[i].x==points[j].x&&points[i].y==points[j].y)
{
same++;
continue;
}
else if(points[i].x==points[j].x) rates[(double)INT_MAX]++;
else
{
double rate=(double)(points[i].y-points[j].y)/double(points[i].x-points[j].x);
if(rates.find(rate)!=rates.end()) rates[rate]++;
else rates[rate]+=2;
}
}
for (auto count : rates) {
/* code */
res=res>count.second+same?res:count.second+same;
}
}
return res;
}
};