149. 直线上最多的点数
题目来源:149. 直线上最多的点数
给你一个数组 points
,其中 points[i] = [xi, yi]
表示 X-Y 平面上的一个点。求最多有多少个点在同一条直线上。
/** * @param {number[][]} points * @return {number} */ var maxPoints = function(points) { let n = points.length; if(n<3) return n; let max = 0; var getKey=(a,b)=>{ let x=a, y=b; while(b!==0){ [a,b]=[b,a%b]; } return a?`${x/a}-${y/a}`:0; } for(let i=0;i<n;i++){ let map = new Map(); let curMax = 1; for(let j=i+1;j<n;j++){ let [x,y]=[points[j][0] - points[i][0], points[j][1] - points[i][1]]; let key = getKey(x,y); //斜率做key map.set(key, (map.get(key)||0) +1); curMax = Math.max(curMax, map.get(key)); } max = Math.max(max, curMax+1); if(max>(n-i-1)){ break; } } return max; }; let points = [[1,1],[2,2],[3,3]] console.log(points, maxPoints(points)) points =[[0,0]] console.log(points, maxPoints(points)) points = [[1,1],[3,2],[5,3],[4,1],[2,3],[1,4]] console.log(points, maxPoints(points)) points = [[4,1],[1,1],[2,3],[1,4],[3,2],[5,3]] console.log(points, maxPoints(points))
示例 1:
输入:points = [[1,1],[2,2],[3,3]] 输出:3
示例 2:
输入:points = [[1,1],[3,2],[5,3],[4,1],[2,3],[1,4]] 输出:4
提示:
1 <= points.length <= 300
points[i].length == 2
-104 <= xi, yi <= 104
points
中的所有点 互不相同