[LeetCode149. 直线上最多的点数] | 刷题打卡

125 阅读1分钟

一、题目描述:

leetcode-cn.com/problems/ma… 给定一个二维平面,平面上有 n 个点,求最多有多少个点在同一条直线上。

****示例 1:

输入: [[1,1],[3,2],[5,3],[4,1],[2,3],[1,4]]
输出: 4
解释:
^
|
|  o
|     o        o
|        o
|  o        o
+------------------->
0  1  2  3  4  5  6

二、思路分析:

  • 直接暴力,定一个点查找斜率相同的点,用一个map记录斜率出现的次数
  • 注意平行于y轴的线,也就是除数为零的情况
  • 用最大公约数化简斜率

三、AC 代码:

/**
 * @param {number[][]} points
 * @return {number}
 */
Math.gcd = function() {
    if (arguments.length == 2) {
        if (arguments[1] == 0)
            return arguments[0];
        else
            return Math.gcd(arguments[1], arguments[0] % arguments[1]);
    } else if (arguments.length > 2) {
        var result = Math.gcd(arguments[0], arguments[1]);
        for (var i = 2; i < arguments.length; i++)
            result = Math.gcd(result, arguments[i]);
        return result;
    }
};

var maxPoints = function(points) {
    let res = 0
    for(let i=0;i<points.length;i++){
        const map  ={}
        let tempRes = 0
        let parallelYaxis = 1
        for(let j=i+1;j<points.length;j++){
            const [x1,y1] = points[i]
            const [x2,y2] = points[j]
            if(x2 === x1){ // 平行与y轴的直线
                parallelYaxis++
                continue
            }
            const gcd = Math.gcd(y2-y1,x2-x1)
            const radio = ((y2-y1)/gcd) / ((x2-x1)/gcd)
            if(map[radio]!==undefined){
                map[radio]++
            }else{
                map[radio] = 1
            }
        }

        for(let key in map){
            tempRes = Math.max(map[key],tempRes)
        }
        res = Math.max(res,parallelYaxis,tempRes+1)


    }

    return res
};

四、总结:

  • 利用辗转相除法求最大公约数
function gcd(a, b) {
    if (b === 0) {
        return a
    }
    return gcd(b, a % b)
}