Max Points on a Line
要点:这题暴力解是用任何两点确定一条直线,然后对其他点检查是否共线,显然,这里没用空间来存储之前的检查结果,所以time complexity是O(n3)。这题的难点是如何存储从而实现O(n2)解。思路是另一种确定一条直线的方法是一点和theta,所以theta可以作为map的key。每次内循环就是检查对于该点下最多共线的点数。
错误点:
- 双循环loop所有pair的方法,inner loop要找外层index的下一个
- hashmap是local的,不是global的
- localmax=1: 这样1个点或者都是相同点可以pass
- theta的计算:对于java,因为坐标是int,必须先用(double) cast,及时theta类型是double。而python没有类型,用float(x-x0)即可
# Definition for a point.
# class Point(object):
# def __init__(self, a=0, b=0):
# self.x = a
# self.y = b
class Solution(object):
def maxPoints(self, points):
"""
:type points: List[Point]
:rtype: int
"""
maxp = 0
for i in range(len(points)):
localmax = 1
hmap = {}
x,y = points[i].x,points[i].y
same = 0
for j in range(i+1, len(points)):
px,py = points[j].x,points[j].y
if px-x==0:
if py==y:
same+=1
continue
else:
theta = float("inf")
else:
theta = (py-y)/float(px-x)
print i,j, theta
if theta not in hmap:
hmap[theta]=2
else:
hmap[theta]+=1
if hmap[theta]>localmax:
localmax = hmap[theta]
if localmax+same>maxp:
maxp = localmax+same
return maxp