Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.
需考虑3类特殊情况:1、x1=x2,斜率无穷大;2、x1=x2,y1=y2,相同点也要计数,当计算最终结果时要加上该值,且相同点个数初始化为1,即其本身;3、y1=y2;
计算斜率时(double)(points[j].y-points[i].y)/(points[j].x-points[i].x)和(double)((points[j].y-points[i].y)/(points[j].x-points[i].x))结果不同,需注意。
1 /** 2 * Definition for a point. 3 * struct Point { 4 * int x; 5 * int y; 6 * Point() : x(0), y(0) {} 7 * Point(int a, int b) : x(a), y(b) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 int maxPoints(vector<Point>& points) { 13 int n=points.size(); 14 if(n<3) return n; 15 int res=0; 16 map<double,int> mp; 17 for(int i=0;i<n-1;i++) 18 { 19 int samepoint=1; 20 int maxpoint=0; 21 int samex=0; 22 23 mp.clear(); 24 map<double,int>::iterator it; 25 for(int j=i+1;j<n;j++) 26 { 27 double slope=0.0; 28 if(i==j) 29 continue; 30 if(points[i].x==points[j].x) 31 { 32 if(points[i].y==points[j].y) 33 samepoint++; 34 else 35 { 36 samex++; 37 maxpoint=max(maxpoint,samex); 38 } 39 continue; 40 } 41 42 43 if(points[i].y==points[j].y) 44 slope=0.0; 45 else 46 slope=(double)(points[j].y-points[i].y)/(points[j].x-points[i].x); 47 it=mp.find(slope); 48 if(it!=mp.end()) 49 it->second+=1; 50 else 51 mp.insert(pair<double,int>(slope,1)); 52 if(mp[slope]>maxpoint) //if(it->second>maxpoint) 53 maxpoint=mp[slope]; //maxpoint=it->second; 结果错误,为6452609,即it=mp.end(),空指针。 54 } 55 maxpoint+=samepoint; 56 res=max(res,maxpoint); 57 } 58 return res; 59 } 60 };