Wednesday, May 7, 2014

LeetCode: 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.

Analysis:

For each point point1, calculate the slope of the lines passing both point1 and all other points. If the slope of two lines are equal, these two lines must the same because they pass the same point with the same slope.

With two points equation, we can get the slope of a line by  (points[i].y-points[j].y)/(points[i].x-points[j].x)

At first I thought the inner loop can be reduce to from i+1 to  points.size()-1, however, the problem of duplicate points cannot be solved this way.

See the code below:

No comments:

Post a Comment