(leetcode)Max Points on a Line
来源:互联网 发布:2017网络语言 编辑:程序博客网 时间:2024/05/20 20:21
Question:
Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.
分析:
1、二维空间的任何一条线都可以表示成为y= k x + b 的形式。两点确定一条直线。固定其中一个点,遍历其余的点,斜率一致的即共线。
2、求斜率时只需遍历当前点与之后的点即可。
3、这里还要考虑斜率不存在的线。
4、还需要统计与当前固定点相同的点的个数。
5、内层遍历完毕即可求出过当前点的线的maxpoints.
6、外层循环遍历所有的点,即求出过所有点的maxpoints。maxpoints 中 的最大值即为所求。
code:
/** * Definition for a point. * struct Point { * int x; * int y; * Point() : x(0), y(0) {} * Point(int a, int b) : x(a), y(b) {} * }; */#define INF 10000000class Solution {public:int maxPoints(vector<Point> &points){ map<double,int> k_slope;//计算斜率相等的点的个数 double k; int n; int MAX = 0; int rex_MAX = 0; map<double,int>::const_iterator C_it;//= k_slope.begin(); for(int i = 0;i<points.size();i++) { n= 0; k_slope.clear(); MAX = 0; for(int j = i+1;j<points.size();j++) { if(points[i].x!=points[j].x) { k = (double)(points[i].y-points[j].y)/(points[i].x-points[j].x); } else if(points[i].y==points[j].y) { n++;//与i点相同的点 continue; } else//x相等,y不相等 { k=INF; } k_slope[k]++; } C_it = k_slope.begin(); for(;C_it!= k_slope.end();C_it++)//取最大值 { if(MAX<C_it->second) MAX = C_it->second; } MAX += n+1;//加上重复的点n以及自身这个点。 if(rex_MAX<MAX) rex_MAX = MAX; } return rex_MAX;//如果points为空返回0,否则即为max points。}};
0 0
- (leetcode)Max Points on a Line
- Max Points on a Line | leetcode
- Max Points on a Line LEETCODE
- Leetcode: Max Points on a Line
- LeetCode - Max Points on a Line
- LeetCode 之 Max Points on a Line
- LeetCode | Max Points on a Line
- [LeetCode] Max Points on a Line
- Leetcode: Max Points on a Line
- LeetCode OJ:Max Points on a Line
- Leetcode Max Points on a Line
- Leetcode: Max Points on a Line .
- [Leetcode] Max Points on a Line (Java)
- leetcode:【Max Points on a Line】
- Max Points on a Line - LeetCode
- LeetCode:Max Points on a Line
- [LeetCode] Max Points on a Line
- leetcode - Max Points on a Line
- 推荐一个博文,适合图像处理初学者
- pl/sql中文显示为乱码
- 三层架构的初步了解
- 模式识别 - 恐怖视频特征训练器 部分实现
- Windows ubuntu共享文件夹 VMware Tools安装 su命令
- (leetcode)Max Points on a Line
- VC++对XML文件操作
- Perl调用外部命令的方式和区别
- poj1837
- 总结如何实现Android浮动层,主要是dialog的使用
- Android手机拍照后照片被旋转的解决
- 2014年4月清明节厦门之旅
- Linux系统故障排查和修复技巧
- ReportStudio入门教程(二十四) - 在报表中引入参数的内容