149. Max Points on a Line
2017-08-06 本文已影响0人
阿发贝塔伽马
Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.
这个题目难不是很难,建立一个dict,斜率:该斜率上点的个数,算斜率特别要注意,如果使用Fraction(3,4),则会非常影响性能,使用np.longdouble(1)满足要求,真是坑爹。
from fractions import Fraction
from collections import defaultdict
import numpy as np
d = defaultdict(lambda: 100)
class Solution(object):
def isequalpt(self, p1, p2):
if p1.x == p2.x and p1.y == p2.y:
return True
else:
return False
def maxPointsatPoint(self, points):
pt = points[0]
del points[0]
i = 0
maxnum = 0
same = 1
dic = defaultdict(lambda: 0)
while i < len(points):
p = points[i]
if self.isequalpt(pt, p):
same += 1
# 并且把p删除
points.remove(p)
continue
if pt.x != p.x:
k = (p.y-pt.y)*np.longdouble(1)/(p.x-pt.x)
dic[k] += 1
maxnum = max(maxnum, dic[k])
else:
dic['zero'] += 1
maxnum = max(maxnum, dic['zero'])
i += 1
maxnum += same
return maxnum
def maxPoints(self, points):
"""
:type points: List[Point]
:rtype: int
"""
lens = len(points)
print lens
if lens < 3:
return lens
self.dic=None
self.maxnumAll = 0
i = 0
while lens > 2:
lr = self.maxPointsatPoint(points)
self.maxnumAll = max(self.maxnumAll, lr)
lens = len(points)
return self.maxnumAll