Given N points on a 2D plane, find the maximum number of points that lie on the same straight line.
When doing this problem, consider a few edge
1. Infinity
2. Same points
Here we save the resulting slope with Hashtable and finally get the maximum value by comparing the number of slope that it has with all the other points.
Algorithm complexity is O (n^2) space complexity is O (n)
The code is as follows:
# Definition for a point# class point:# def __init__ (self, a=0, b=0): # self.x = a# Self.y = Bclass Sol Ution: # @param points, a list of points # @return an integer def maxpoints (self, points): #slop ={} Maxp=0 If Len (points) <3:return Len (points) for I in range (len (points)): Samepoint =1 slope={' inf ': 0} for J in range (Len (points)): if I==j:continue Elif points[i].x==points[j].x and Points[i].y==points[j].y:samepoint+=1 Elif points[i].x==points[j].x and points[i].y!=points[j].y:slope[' inf ']+=1 else: k=1.0* (POINTS[I].Y-POINTS[J].Y)/(points[i].x-points[j].x) if k not in slope: Slope[k]=1 else:slope[k]+=1 Maxp=max (Maxp,max (slope.values ()) +samepoint) reTurn MAXP
Max Points on a line leetcode Python