Leetcode: Max Points on a Line
2015-08-09 19:09
465 查看
Given n points
on a 2D plane, find the maximum number of points that lie on the same straight line.
分析:
任意一条直线都可以表述为
y = ax + b
假设,有两个点(x1,y1), (x2,y2),如果他们都在这条直线上则有
y1 = kx1 +b
y2 = kx2 +b
由此可以得到关系,k = (y2-y1)/(x2-x1)。即如果点c和点a的斜率为k, 而点b和点a的斜率也为k,可以知道点c和点b也在一条线上。
取定一个点points[i], 遍历其他所有节点, 然后统计斜率相同的点数,并求取最大值即可
注意三个地方:
1、如果点的数目小于3个,则最大数目为点的个数。
2、考虑重复点的情况,重复点是无法计算斜率的。
3、考虑直线与y轴平行时,斜率为无穷大的情况。
on a 2D plane, find the maximum number of points that lie on the same straight line.
分析:
任意一条直线都可以表述为
y = ax + b
假设,有两个点(x1,y1), (x2,y2),如果他们都在这条直线上则有
y1 = kx1 +b
y2 = kx2 +b
由此可以得到关系,k = (y2-y1)/(x2-x1)。即如果点c和点a的斜率为k, 而点b和点a的斜率也为k,可以知道点c和点b也在一条线上。
取定一个点points[i], 遍历其他所有节点, 然后统计斜率相同的点数,并求取最大值即可
注意三个地方:
1、如果点的数目小于3个,则最大数目为点的个数。
2、考虑重复点的情况,重复点是无法计算斜率的。
3、考虑直线与y轴平行时,斜率为无穷大的情况。
/** * 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) { // IMPORTANT: Please reset any member data you declared, as // the same Solution instance will be reused for each test case. unordered_map<float,int> mp; int maxNum = 0; for(int i = 0; i < points.size(); i++) { mp.clear(); mp[INT_MIN] = 0; int duplicate = 1; for(int j = 0; j < points.size(); j++) { if(j == i) continue; if(points[i].x == points[j].x && points[i].y == points[j].y) { duplicate++; continue; } float k = points[i].x == points[j].x ? INT_MAX : (float)(points[j].y - points[i].y)/(points[j].x - points[i].x); mp[k]++; } unordered_map<float, int>::iterator it = mp.begin(); for(; it != mp.end(); it++) if(it->second + duplicate > maxNum) maxNum = it->second + duplicate; } return maxNum; } };
相关文章推荐
- HDU1429 胜利大逃亡
- poj 2299树状数组求逆序数
- 老版本上的兼容ripple效果以及通用selecter
- Objective-C学习笔记_类的扩展
- poj 1328Radar Installation
- tomcat整合apache
- tomcat整合apache
- Unix环境高级编程:进程控制-线程控制-僵尸进程
- Struts2 入门实例
- 基于Wi-Fi的室内定位在美团总部的实践和应用
- 华为上机 最小长方形 java
- 从WebView到http协议
- 回归研发一线
- Java笔试面试题004
- GlTail.rb : 超 Geek 的可视化日志分析工具
- HDU 5366 【组合数+隔板法】
- 排序一 简单排序
- Socket套接字
- LintCode-通配符匹配
- Java注解之分类