Max Points on a Line
2015-10-12 21:50
357 查看
题目149:Max Points on a Line
Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.题目分析:
计算在在一条直线上的点最多的个数。
两个不同的点A、B确定一条直线,这是显然的,如何判断第三个点C,在这两个点确定的一条直线上,如果A和C的斜率等于A和B的斜率,则C在A和B确定的直线上。
好了,该题有思路了,参考[2]思路写的清晰,参考[1]代码写的清晰,是我的喜欢的风格,希望自己代码也可以写的这么清晰。
思路分析:
以某点O为中心,计算它和其他所有点的斜率,如果直线OA的斜率等于直线OB的斜率,则OAB三点公线,求出包括O点的直线上包含点最多的个数K(O);
再依次求出包含剩余点的直线上包含点最多的个数,取最大值得出结果,时间复杂度是O(N^2)。
因为每次求斜率都要比较是否有相等的斜率,再修改统计的个数,所以为了效率,可以采用哈希表来保存斜率值,unordered_map< float slope, int count>。
如果有重复的点,要统计重复的点的个数dup,则实际在同一条直线上点的个数是K(O) + dup。
这里为了避免重复计算,以数组中第i个点为中心时,只计算数组中它右边的所有点(为什么这么做对,因为只求max,max肯定也是大于前面求过的值的)
代码如下:
/** * 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 len = points.size(); /* 注释(1) */ if (len <= 2) return len; int max = 0; unordered_map<float, int> mp; for (int i = 0; i < len; i ++) { mp.clear(); /* 注释(2) */ int dup = 1; /* 注释(3) */ mp[INT_MIN] = 0; for (int j = i + 1; j < len; j ++) { if (points[i].x == points[j].x && points[i].y == points[j].y) { ++ dup; continue; } /* 注释(4) */ float slope = (points[i].x == points[j].x) ? INT_MAX : (float)(points[i].y - points[j].y) / (points[i].x - points[j].x); mp[slope] ++; } unordered_map<float, int>::iterator iter = mp.begin(); for (; iter != mp.end(); iter ++) if (iter->second + dup > max) max = iter->second + dup; } return max; } };
注释:
(1)如果点数少于2个,直接返回点的个数,两个点才可以确定一条直线;
(2)dup为什么初始化是1,这个如果是3个点时,两个点重复,应该返回3,如果dup初始化是0,则返回2,错误,因为两个点确定一条直线,少算了当前点;
(3)mp[INT_MIN],如果都是重复的点,则mp是空,iter是空,返回max是0,错误;
(4)斜率是无穷大还是正常取值;
参考:
[1] http://blog.csdn.net/doc_sgl/article/details/17103427
[2] http://www.cnblogs.com/TenosDoIt/p/3444086.html
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解
- LeetCode [Day 5] Longest Palindromic Substring 题解