Max Points on a Line

Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.

找一个二维图上在一条直线上点的最大数,不知道有啥更好的方法。

需要注意重复点的情况

 1 class Solution {
 2 public:
 3     int maxPoints(vector<Point> &points) {
 4         if(points.size()<=2) {
 5             //3个点以下
 6             return points.size();
 7         } else {
 8             int maxNum = 2;
 9             //选择一个点为出发点计算所有斜率
10             for(vector<Point>::iterator point = points.begin(); point!=points.end(); ++point) {
11                 map<double,int> kMap;
12                 int numOfSame = 0; 
13                 for(vector<Point>::iterator otherPoint = points.begin(); otherPoint!=points.end(); ++otherPoint) {
14                     //跳过出发点
15                     if(otherPoint==point) continue; 
16                     //记录重复点数量
17                     if(otherPoint->x == point->x && otherPoint->y == point->y) {
18                         ++numOfSame;
19                         continue;
20                     }
21                     double k = otherPoint->x - point->x == 0 ?
22                                numeric_limits<double>::max()
23                                :(otherPoint->y - point->y)/(double)(otherPoint->x-point->x);
24                     if(kMap.find(k)==kMap.end()) kMap[k]=0;
25                     ++kMap[k];
26                 }
27 
28                 auto tmpMax = max_element(kMap.begin(),kMap.end(),[&](pair<const double,int> &l,pair<const double,int> &r) {
29                     return l.second < r.second;
30                 });
31 
32                 maxNum = tmpMax!=kMap.end()?
33                                  max(tmpMax->second+1+numOfSame,maxNum):
34                                  max(1+numOfSame,maxNum);
35             }
36             return maxNum ;
37         }
38     }
39 };

 

 

 



 

posted @ 2014-10-22 16:09  Madao_  阅读(149)  评论(0)    收藏  举报