Leetcode——Max Points on a Line
Leetcode题解——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.
题目理解:
这次的题目描述十分的简短,也很好理解,给一个二维平面点的集合,找出这些点最多有多少个点在同一平面。
思路:
一开始的思路就是暴力解决咯,对于每一个点遍历一下它和其他所有的点之间的斜率,斜率相同的就是在同一条直线上咯,这样的话时间复杂度是O(n^2),也许有更好的方法,但是我实在是想不到怎么去用更好的方法了。然而斜率要注意的就是斜率不存在的情况,以及有可能有重复点的情况。
算法:
可以先把点都排个序,这样方便计算斜率,之后就是去重,去完重就可以欢快的遍历了
/** * 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: struct K{ int dy; int dx; K(){} K(int y,int x){ if(x<0){ dy = -y; dx = -x; }else{ dy = y; dx = x; } } bool operator<(const K& b) const{ return dy*b.dx<dx*b.dy; } };//定义斜率,并且重载操作符 int maxPoints(vector<Point> &points) { int l = points.size(); if(l<=2){ return l; } sort(points.begin(),points.end(),[](const Point& a,const Point& b)->bool{ return a.x<b.x||a.x==b.x&&a.y<b.y; });//排序,方便之后的计算 vector<int> Reaptcount; vector<Point> realPoint;//去重之后的集合 realPoint.push_back(points[0]); Reaptcount.push_back(1); Point last = points[0]; for(int i=1;i<l;i++){ if(points[i].x==last.x&&points[i].y==last.y){ Reaptcount.back()++; }else{ last = points[i]; Reaptcount.push_back(1); realPoint.push_back(points[i]); } }//去重,把重复点去掉 int real_len = realPoint.size(); map<K,int> kf;//映射,斜率到点的映射 int gmax = Reaptcount[0];//gmax就是最大点数目 for(int i=0;i<real_len-1;i++){ int verticalCount = 0; for(int j=i+1;j<real_len;j++){ int cc = Reaptcount[j]; int dx = realPoint[i].x - realPoint[j].x; int dy = realPoint[i].y - realPoint[j].y; if(dx==0){ verticalCount+=cc; continue; } K k(dx,dy); if(kf.find(k)!=kf.end()){ kf[k]+=cc; }else{ kf[k]=cc; } } int tmax = verticalCount; for(map<K,int>::iterator it=kf.begin();it!=kf.end();it++){ if(it->second>tmax){ tmax = it->second; } } if(tmax+Reaptcount[i]>gmax){ gmax = tmax+Reaptcount[i]; } kf.clear(); } return gmax; } };
posted on 2015-12-11 01:01 MasnVulcan 阅读(63) 评论(0) 收藏 举报
浙公网安备 33010602011771号