149. Max Points on a Line

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.

Example 1:

Input: [[1,1],[2,2],[3,3]]
Output: 3
Explanation:
^
|
|        o
|     o
|  o  
+------------->
0  1  2  3  4

Example 2:

Input: [[1,1],[3,2],[5,3],[4,1],[2,3],[1,4]]
Output: 4
Explanation:
^
|
|  o
|     o        o
|        o
|  o        o
+------------------->
0  1  2  3  4  5  6

NOTE: input types have been changed on April 15, 2019. Please reset to default code definition to get new method signature.

方法1:

huahua:https://zxi.mytechroad.com/blog/geometry/leetcode-149-max-points-on-a-line/

思路:

两点确定一线后,如何判断第三点是否与他们共线?关键在于比较slope。如果两对点的slope一样,可以判断这两条线段共线。为了避免floating造成的误差,这里需要用pair<int, int>来标示slope,建立hash 进行计数。最后的结果是基于最高频出现的slope数量而决定的。为了使{6, 2}, {3, 1}被map到同一个结果,需要对pair求gcd,normailzie一下再存入hash。这里用一个子函数gcd来递归求解。由于我们的目的是枚举所有两点之间的slope,所以整体遍历采用双层循环,每次 i 和他后面的所有点求slope即可。这里求解slope要处理三种特殊情况:1. 重合点,2. 垂直线,3. 水平线。其中duplicates可以直接被叠加计数,最后统一处理。而另外两种情况也被用{x, 0}, {y, 0}形式被hash。在内循环中随时记录一个极值点,出循环后和全球变量在总结一次极值。duplicates直接在外层循环中被累加即可。

易错点:

  1. duplicates的初始值是1: 在 i 的循环内,对每一个在 i 后面的点 j 之间的slope计数,最后提取出的结果是和 i 共线的其他点数,还没有算 i 自己。而其他所有和 i 重合的点,也都应该一起被计数。
  2. slope的计算:要处理三种特殊情况,首先排除duplicates,然后是vertical,直接返回{x, 0}, 如果是horizontal,直接返回{0 , y},否者要将slope pair用gcd函数的返回值normalize一下再返回主函数,存进 hash。
  3. gcd的递归形式:经典写法。

Complexity

Time complexity: O(n^2)
Space complexity: O(n)

class Solution {
public:
    int maxPoints(vector<vector<int>>& points) {
        int n = points.size();
        int result = 0;
        for (int i = 0; i < n; i++) {
            map<pair<int, int>, int> hash;
            int duplicates = 1;
            int current = 0;
            for (int j = i + 1; j < n; j++) {
                if (points[i] == points[j]) duplicates++;
                else {
                    pair<int, int> slope = getSlope(points[i], points[j]);
                    hash[slope]++;
                    current = max(current, hash[slope]);
                }
            }
            result = max(result, current + duplicates);
        }
        return result;
    }
    
    pair<int, int> getSlope(vector<int> & a, vector<int> & b) {
        // vertical line
        if (a[0] == b[0]) return {a[0], 0};
        // horizontal line
        if (a[1] == b[1]) return {0, a[1]};
        // find gcd
        int d = gcd(a[1] - b[1], a[0] - b[0]);
        // return normalized slope pair
        return {(a[1] - b[1]) / d, (a[0] - b[0]) / d};
    }
    
    int gcd(int m, int n){
       return (n == 0) ? m : gcd(n, m % n); 
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值