Given n points
on a 2D plane, find the maximum number of points that lie on the same straight line.
給定2維平面的N個點,找出共線的最多的點。
分析如下,初中知識,任何不相同的兩點確定一條直線。
特殊情況,如果n <=2,共線的點n。
如果n>2怎麼辦呢? 給定三個點<x1, y1>, <x2, y2>, <x3, y3>,如果共線,我們會發現slop=(y2 -y1)/(x2-x1) = (y3 - y1)/(x3 - x1)。 請注意特殊情況如果三個點x值相同。
一下是c++程序.
/**
* 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) {
//special case
if(points.size() <= 2) return points.size();
int i, j, repeat, spc, max = 0;
map<double, int> stat;
for(i = 0; i < points.size(); i++){
//fix each point, find the point
repeat = 0;
spc = 0;
stat.clear();
Point point = points[i];
for(j = 0; j < points.size(); j++){
//if(i == j) continue;
Point p2 = points[j];
if(point.x == p2.x){
if(point.y == p2.y) repeat++; //also add self
else spc++;
}else{
stat[(double)(p2.y-point.y)/(p2.x - point.x)] ++;
}
}
for(map<double,int>::iterator begin = stat.begin(); begin != stat.end(); begin++){
if(begin->second > spc) spc = begin->second;
}
if(max < (spc + repeat))max = spc + repeat;
}
return max;
}
};