LeetCode:149_Max Points on a line | 寻找一条直线上最多点的数量 | Hard
2014-09-26 18:27
447 查看
题目:Max Points on a line
这道题需要稍微转变一下思路,用斜率来实现,试想找在同一条直线上的点,怎么判断在一条直线上,唯一的方式也只有斜率可以完成,我开始没想到,后来看网友的思路才想到的,下面是简单的实现:
其中有一点小技巧,利用map<double, int>来存储具有相同斜率值的的点的数量,简洁高效。
Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.
这道题需要稍微转变一下思路,用斜率来实现,试想找在同一条直线上的点,怎么判断在一条直线上,唯一的方式也只有斜率可以完成,我开始没想到,后来看网友的思路才想到的,下面是简单的实现:
其中有一点小技巧,利用map<double, int>来存储具有相同斜率值的的点的数量,简洁高效。
/* Definition for a point */ // struct Point { // int x; // int y; // Point():x(0),y(0) {} // Point (int a, int b):x(0), y(0) {} // }; int maxPoints(vector<Point> &points) { if (points.empty()) return 0; if (points.size() <= 2) return points.size(); int numPoints = points.size(); map<double, int> pmap; //存储斜率-点数对应值 int numMaxPoints = 0; for (int i = 0; i != numPoints - 1; ++i) { int numSamePoints = 0, numVerPoints = 0; //针对每个点分别做处理 pmap.clear(); for (int j = i + 1; j != numPoints; ++j) { if(points[i].x != points[j].x) { double slope = (double)(points[j].y - points[i].y) / (points[j].x - points[i].x); if (pmap.find(slope) != pmap.end()) ++ pmap[slope]; //具有相同斜率值的点数累加 else pmap[slope] = 1; } else if (points[i].y == points[j].y) numSamePoints ++; //重合的点 else numVerPoints ++; //垂直的点 } map<double, int>::iterator it = pmap.begin(); for (; it != pmap.end(); ++ it) { if (it->second > numVerPoints) numVerPoints = it->second; } if (numVerPoints + numSamePoints > numMaxPoints) numMaxPoints = numVerPoints + numSamePoints; } return numMaxPoints + 1; }
相关文章推荐
- LeetCode | 149. Max Points on a Line求多个点里面在一条直线上的点最多有多少个难题
- [leetcode] Max Points on a Line 判断最多有多少个点在同一条直线上
- Leetcode 149. Max Points on a Line (Hard) (cpp)
- 【LeetCode】max-points-on-a-line一条线上最多点
- lintcode 中等题:Max Points on a Line 最多有多少个点在一条直线上
- LeetCode 149. Max Points on a Line(直线上的点)
- leetcode 149 —— Max Points on a Line
- 【leetcode】Max Points on a Line(hard)☆
- 找出穿过最多点的直线 Max Points on a Line
- LeetCode149:Max Points on a Line
- [LeetCode]149 Max Points on a Line
- [leetcode-149]Max Points on a Line(java)
- LeetCode(149) Max Points on a Line
- LeetCode: Max Points on a Line [149]
- [leetcode] 149. Max Points on a Line
- leetcode 149: Max Points on a Line
- leetcode 149:Max Points on a Line(java实现)细致分析
- leetcode 149. Max Points on a Line
- LeetCode(149) Max Points on a Line
- leetcode ex3 找出穿过最多点的直线 Max Points on a Line