Max Points on a Line
2015-07-31 16:52
239 查看
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))结果不同,需注意。
需考虑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))结果不同,需注意。
/** * 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) { int n=points.size(); if(n<3) return n; int res=0; map<double,int> mp; for(int i=0;i<n-1;i++) { int samepoint=1; int maxpoint=0; int samex=0; mp.clear(); map<double,int>::iterator it; for(int j=i+1;j<n;j++) { double slope=0.0; if(i==j) continue; if(points[i].x==points[j].x) { if(points[i].y==points[j].y) samepoint++; else { samex++; maxpoint=max(maxpoint,samex); } continue; } if(points[i].y==points[j].y) slope=0.0; else slope=(double)(points[j].y-points[i].y)/(points[j].x-points[i].x); it=mp.find(slope); if(it!=mp.end()) it->second+=1; else mp.insert(pair<double,int>(slope,1)); if(mp[slope]>maxpoint) //if(it->second>maxpoint) maxpoint=mp[slope]; //maxpoint=it->second; 结果错误,为6452609,即it=mp.end(),空指针。 } maxpoint+=samepoint; res=max(res,maxpoint); } return res; } };
相关文章推荐
- Android studio 使用心得(五)—代码混淆和破解apk
- Android studio 使用心得(四)—android studio 多渠道打包(二)
- LTView
- 暑假集训第三周第二阶段 搜索 J - 放苹果
- spring, hibernate 事物处理,异常拦截
- 20150729 DOM事件探秘
- 关于linux服务配置的问题 starting MySQL.Manager of pid-file quit without updating fi[failed]
- 如果让我重新设计一款Android App
- 枚举值的使用
- 【Android应用开发技术:用户界面】SurfaceView
- 2015安徽省赛 B.求和
- Android studio 使用心得(三)—从Eclipse迁移到Android studio
- yum搭建svn apache 利用钩子检出到web目录 自动同步
- UVA 784 Maze Exploration
- java缓存(2、ThreadLocal<T>)
- CF_405B_DominoEffect
- hdu 2187 悼念512汶川大地震遇难同胞——老人是真饿了
- 关于android系统不关屏设置
- 获取CAD安装路径
- 查缺补漏中~~