[LeetCode][JavaScript]Max Points on a Line
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.
求有多少点在一直线上。
粗暴地用二重循环遍历。
每一轮都构造一个哈希表,用来记录斜率,斜率k = (y1 - y2) / (x1 - x2)。
注意到特殊情况:
1.两点重合,用countSamePoint记下重复的点,最后加到结果上。
2.两点与X轴平行,此时y1 - y2 = 0, k = 0,构造哈希表,提前塞一个slopeMap[0] = 0。
3.两点与Y轴平行,此时x1 - x2 = 0, k = Infinity,同上塞一个slopeMap[Infinity] = 0。
1 /** 2 * Definition for a point. 3 * function Point(x, y) { 4 * this.x = x; 5 * this.x = y; 6 * } 7 */ 8 /** 9 * @param {Point[]} points 10 * @return {number} 11 */ 12 var maxPoints = function(points) { 13 if(points.length <= 1){ 14 return points.length; 15 } 16 var res = -1, countSamePoint, max, i, j, slopeMap, curr, slope, tmp; 17 for(i = 0; i < points.length; i++){ 18 curr = points[i]; 19 max = 0; 20 countSamePoint = 1; 21 slopeMap = {}; 22 slopeMap[0] = 0; slopeMap[Infinity] = 0; 23 for(j = 0; j < points.length; j++){ 24 if(i === j){ 25 continue; 26 } 27 if(points[j].x === curr.x && points[j].y === curr.y){ 28 countSamePoint++; 29 }else{ 30 slope = (points[j].y - curr.y) / (points[j].x - curr.x); 31 if(slopeMap[slope] === undefined){ 32 slopeMap[slope] = 1; 33 }else{ 34 slopeMap[slope]++; 35 } 36 tmp = slopeMap[slope]; 37 if(tmp > max){ 38 max = tmp; 39 } 40 } 41 if(max + countSamePoint > res){ 42 res = max + countSamePoint; 43 } 44 } 45 } 46 return res; 47 };
Test Cases:
1 function test(){ 2 console.log(maxPoints([])); //0 3 console.log(maxPoints([new Point(0,0)])); //1 4 console.log(maxPoints([new Point(0,0),new Point(0,0)])); //2 5 console.log(maxPoints([new Point(1,1),new Point(2,1)])); //2 6 console.log(maxPoints([new Point(1,1),new Point(1,2)])); //2 7 console.log(maxPoints([new Point(0,0),new Point(1,1),new Point(0,0)])); //3 8 console.log(maxPoints([new Point(1,1),new Point(2,2),new Point(2,3),new Point(3,3),new Point(5,10)])); //3 9 console.log(maxPoints([new Point(1,1),new Point(1,1),new Point(2,2),new Point(2,2)])); //4 10 11 };