给出二维平面上的n个点,求最多有多少点在同一条直线上。
您在真实的面试中是否遇到过这个题?
样例
给出4个点:(1, 2)
, (3, 6)
, (0, 0)
, (1, 3)
。
一条直线上的点最多有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
const int n=points.size();
if(1==n)
return 1;
if(0==n)
return 0;
double k[n][n];
map<double,int> nums;
int maxp=1;
for(int i=0;i<n;++i){
int sam=1;
for(int j=i+1;j<n;++j){
if(points[i].x==points[j].x&&points[i].y==points[j].y){
++sam;
continue;
}else if(points[i].x==points[j].x){
k[i][j]=INT_MAX;
}else{
k[i][j]=(points[i].y-points[j].y)*1.0/(points[i].x-points[j].x);
}
++nums[k[i][j]];
}
int sum=-INT_MIN;
maxp=max(sam,maxp);
for(auto e:nums){
if(e.second+sam>sum)
sum=e.second+sam;
}
nums.clear();
if(sum>maxp)
maxp=sum;
}
return maxp;
}
};