Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.
算法思想:
对于节点序列points,对于每一个节点,从它的后一个节点开始往后遍历,与当前节点斜率相同的放一组,遍历完找到与当前节点相连最多的那一组元素个数作为过当前节点一条线上的最多点数。
有几点注意事项:1、垂线的处理,这里可以用PI(3.1415926)来表示(因为只要是斜率必然是有限小数或者无限循环小数,况且这些都是整数点)2、相同的点的处理
3、需要一些剪枝,否则会TLE,把一些不可能情况排除,比如说对于序列<1,2,3,4,5,6,7>,这七个点,如果我们已经找到3个点在一条线上,那么我们就没必要对5,6,7这3个点往后遍历找最长的点个数了,因为对于5来说最多也只能有3个点在一条线上(5,6,7而已)
/**
* Definition for a point.
* struct Point {
* int x;
* int y;
* Point() : x(0), y(0) {}
* Point(int a, int b) : x(a), y(b) {}
* };
*/
#include <map>
#include <cmath>
#define PI 3.1415926
class Solution {
public:
int maxV(map<double,int> t){
int v=0;
map<double,int>::iterator it;
for(it=t.begin();it!=t.end();it++){
v=v<it->second?it->second:v;
}
return v;
}
int maxPoints(vector<Point> &points){
int maxP=0;
for(int i=0;i<points.size()-maxP;i++){
int con=0;
map<double,int> m;
map<double,int>::iterator it;
for(int j=i+1;j<points.size();j++){
int x=points[i].x-points[j].x;
int y=points[i].y-points[j].y;
double k;
if(x==0&&y==0){
con++;
continue;
}
if(x==0){
k=PI;
}
else k=y*1.0/x;
//cout<<k<<endl;
it=m.find(k);
if(it!=m.end()){
it->second++;
}
else {
m.insert(pair<double,int>(k,1));
}
}
maxP=maxP<1+con+maxV(m)?1+con+maxV(m):maxP;
}
return maxP;
}
};