[leetcode] 149. Max Points on a Line
来源:互联网 发布:semantic ui 怎么 js 编辑:程序博客网 时间:2024/04/19 12:21
Givenn points on a 2D plane, find the maximum number of points that lie on the same straight line.
这道题给出平面坐标系上的n个点,找出一条直线最多穿过多少这些已知的点。题目难度为Hard。
乍看起来可能无从下手,不过通过直线坐标公式y=kx+b可以知道通过一个固定点的直线可以用它的斜率k区分。这样我们可以固定一个点,然后计算其他点和它确定的直线斜率,相同斜率的必定在同一条直线上。遍历所有点,通过斜率区分通过它的直线。遍历到后续的点时不必考虑它之前的点,因为这些直线已经检查过了。至此大家应该已经想到了用HashTable来解决问题,遍历每个点,将通过这个点的所有直线斜率存入HashTable,如果斜率存在说明在同一条直线上。
这里有两点需要注意:
题目没有说明所有点不重复,可能有重复的点;
平行y轴的直线没有斜率,不能存入HashTable,要特殊处理。
具体代码:
/** * 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 maxNum = 0; if(points.size() == 0) return 0; if(points.size() == 1) maxNum = 1; for(int i=0; i<points.size(); i++) { unordered_map<double, int> hash; int sameX = 0; //e.g. line x=5 int samePoint = 1; for(int j=i+1; j<points.size(); j++) { if(points[i].x == points[j].x && points[i].y == points[j].y) { samePoint++; } else if(points[i].x == points[j].x) { sameX++; } else { double k = (double)(points[j].y - points[i].y) / (double)(points[j].x - points[i].x); if(hash.find(k) == hash.end()) hash[k] = 1; else hash[k]++; } } for(auto it = hash.begin(); it != hash.end(); it++) { maxNum = max(maxNum, it->second + samePoint); } maxNum = max(maxNum, sameX + samePoint); } return maxNum; }};
0 0
- LeetCode 149. Max Points on a Line
- [leetcode] 149. Max Points on a Line
- leetcode 149. Max Points on a Line
- Leetcode 149. Max Points on a Line
- LeetCode 149. Max Points on a Line
- leetcode.149. Max Points on a Line
- LeetCode-149.Max Points on a Line
- leetcode 149. Max Points on a Line
- leetCode 149. Max Points on a Line
- [LeetCode] 149. Max Points on a Line
- LeetCode 149. Max Points on a Line
- [LeetCode]149. Max Points on a Line
- [LeetCode]149. Max Points on a Line
- [LeetCode]149. Max Points on a Line
- Leetcode 149. Max Points on a Line
- [LeetCode] 149. Max Points on a Line
- Leetcode 149. Max Points on a Line
- 【LeetCode】149. Max Points on a Line
- 苹果Mac安装Dr.com
- STL中set的相关运用
- hdu 1856 并查序 特殊优化
- python初级了解
- 我的dubbo学习笔记
- [leetcode] 149. Max Points on a Line
- Unity3D 关于刚体(RigitBody)与碰撞体(Collider)的探索
- 长见错误
- LightOJ 1013 - Love Calculator
- 字符分割方法1
- 1101. Quick Sort (25)
- 如何同步openstack RDO源至本地进行离线安装
- Weblogic Security Realm:weblogic安全领域及账号管理实用工具剖析
- Oracle ORA-06502 数字或值错误:字符串缓冲区太小