[LeetCode] Max Points on a Line
2015-05-25 14:32
411 查看
Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.
经过同一个点且斜率相等的直线一定是同一条直线,所以我们只要分别计算每一个点与其它点的直线的斜率,统计斜率的个数,找出最大值。可以使用double来表示斜率,使用map<double, int>来统计个数。但是有两点要注意,那就是:
(1) 如果直线与x轴垂直,此时斜率是无穷大,要单独处理
(2) 所给的点中有些是相同的点,此时也要特殊处理一下。
经过同一个点且斜率相等的直线一定是同一条直线,所以我们只要分别计算每一个点与其它点的直线的斜率,统计斜率的个数,找出最大值。可以使用double来表示斜率,使用map<double, int>来统计个数。但是有两点要注意,那就是:
(1) 如果直线与x轴垂直,此时斜率是无穷大,要单独处理
(2) 所给的点中有些是相同的点,此时也要特殊处理一下。
/** * 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 res = 0, same_cnt, ver_cnt, cnt; unordered_map<double, int> mp; double k; for (int i = 0; i < points.size(); ++i) { same_cnt = ver_cnt = cnt = 0; mp.clear(); for (int j = 0; j < points.size(); ++j) { if (points[i].x == points[j].x) { if (points[i].y == points[j].y) { ++same_cnt; continue; }else { ++ver_cnt; cnt = max(cnt, ver_cnt); } } else { k = (double) (points[i].y - points[j].y) / (points[i].x - points[j].x); ++mp[k]; cnt = max(cnt, mp[k]); } } res = max(res, cnt + same_cnt); } return res; } };
相关文章推荐
- [LeetCode]Max Points on a Line
- [Leetcode]149. Max Points on a Line @python
- LeetCode | Max Points on a Line
- 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]149. 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
- Max Points on a Line --- LeetCode 面试题
- leetcode 149. Max Points on a Line
- 【LeetCode】-Max Points on a Line
- LeetCode:149_Max Points on a line | 寻找一条直线上最多点的数量 | Hard
- [leetcode] Max Points on a Line
- leetcode 149. Max Points on a Line
- leetcode Max Points on a Line
- leetcode Max Points on a Line