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.
Ask how many points are on the line.
Traverse it rudely with a double loop.
Each round is constructed with a hash table to record the slope, the slope k = (y1-y2)/(X1-X2).
Note the special case:
1. Two points coincident, with Countsamepoint note the repeated points, and finally added to the results.
2. Two points parallel to the x-axis, at this time Y1-y2 = 0, k = 0, constructs a hash table, and plugs a slopemap[0] = 0 in advance.
3. The two point is parallel to the y-axis, at which point x1-x2 = 0, k = Infinity, and the same as plug one 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[]} pointsTen * @return {number} One */ A varMaxpoints =function(points) { - if(Points.length <= 1){ - returnpoints.length; the } - varres =-1, Countsamepoint, Max, I, J, Slopemap, Curr, Slope, tmp; - for(i = 0; i < points.length; i++){ -Curr =Points[i]; +Max = 0; -Countsamepoint = 1; +Slopemap = {}; ASlopemap[0] = 0; Slopemap[infinity] = 0; at for(j = 0; J < Points.length; J + +){ - if(i = = =j) { - Continue; - } - if(points[j].x = = = Curr.x && Points[j].y = = =curr.y) { -countsamepoint++; in}Else{ -Slope = (POINTS[J].Y-CURR.Y)/(Points[j].x-curr.x); to if(Slopemap[slope] = = =undefined) { +Slopemap[slope] = 1; -}Else{ theslopemap[slope]++; * } $TMP =Slopemap[slope];Panax Notoginseng if(tmp >max) { -Max =tmp; the } + } A if(max + Countsamepoint >Res) { theres = max +Countsamepoint; + } - } $ } $ returnRes; -};
Test Cases:
1 functionTest () {2Console.log (Maxpoints ([]));//03Console.log (Maxpoints ([NewPoint (0,0)]);//14Console.log (Maxpoints ([NewPoint (0,0),NewPoint (0,0)]);//25Console.log (Maxpoints ([NewPoint (+),NewPoint (2,1)]);//26Console.log (Maxpoints ([NewPoint (+),NewPoint ()));//27Console.log (Maxpoints ([NewPoint (0,0),NewPoint (+),NewPoint (0,0)]);//38Console.log (Maxpoints ([NewPoint (+),NewPoint (2,2),NewPoint (2,3),NewPoint (3,3),NewPoint (5,10)]);//39Console.log (Maxpoints ([NewPoint (+),NewPoint (+),NewPoint (2,2),NewPoint (2,2)]);//4Ten One};
[Leetcode] [JavaScript] Max Points on a line