[LeetCode] 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.

 

这道题给了我们一堆二维点,然后让我们求最大的共线点的个数,根据初中数学我们知道,两点确定一条直线,而且可以写成y = ax + b的形式,所有共线的点都满足这个公式。所以这些给定点两两之间都可以算一个斜率,每个斜率代表一条直线,对每一条直线,带入所有的点看是否共线并计算个数,这是整体的思路。但是还有两点特殊情况需要考虑,二是当两个点重合时,无法确定一条直线,但这也是共线的情况,需要特殊处理。二是斜率不存在的情况,由于两个点(x1, y1)和(x2, y2)的斜率k表示为(y2 - y1) / (x2 - x1),那么当x1 = x2时斜率不存在,这种共线情况需要特殊处理。我们需要用到哈希表来记录斜率和共线点个数之间的映射,其中第一种重合点的情况我们假定其斜率为INT_MIN,第二种情况我们假定其斜率为INT_MAX,这样都可以用map映射了。我们还需要顶一个变量duplicate来记录重合点的个数,最后只需和哈希表中的数字相加即为共线点的总数。代码如下:

 

/**
 * 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;
        unordered_map<float, int> m;
        for (int i = 0; i < points.size(); ++i) {
            m.clear();
            m[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 slope = (points[i].x == points[j].x) ? INT_MAX : (float)(points[j].y - points[i].y) / (points[j].x - points[i].x);
                ++m[slope];
            }
            for (unordered_map<float, int>::iterator it = m.begin(); it != m.end(); ++it) {
                res = max(res, it->second + duplicate);
            }
        }
        return res;
    }
};

 

参考资料:

http://huntfor.iteye.com/blog/2087070

http://fisherlei.blogspot.com/2013/12/leetcode-max-points-on-line-solution.html

http://www.cnblogs.com/TenosDoIt/p/3444086.html

https://leetcode.com/discuss/33633/20-line-c-o-n-2-hashing-solution

 

LeetCode All in One 题目讲解汇总(持续更新中...)

你可能感兴趣的:(LeetCode)