【leetcode】Max Points on a Line

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.

解题思路:

1.首先由这么一个O(n^3)的方法,也就是算出每条线的方程(n^2),然后判断有多少点在每条线上(N)。这个方法肯定是可行的,只是复杂度太高
2.然后想到一个O(N)的,对每一个点,分别计算这个点和其他所有点构成的斜率,具有相同斜率最多的点所构成的直线,就是具有最多点的直线。

注意的地方:

1.重合的点
2.斜率不存在的点

 # Definition for a point
class Point:
def __init__(self, a=0, b=0):
self.x = a
self.y = b class Solution:
# @param points, a list of Points
# @return an integer
def calcK(self,pa, pb):
t = ((pb.y - pa.y) * 1.0) / (pb.x - pa.x)
return t def maxPoints(self, points):
l = len(points)
res = 0
if l <= 2:
return l
for i in xrange(l):
same = 0
k = {}
k['inf'] = 0
for j in xrange(l):
if points[j].x == points[i].x and points[j].y != points[i].y:
k['inf'] += 1
elif points[j].x == points[i].x and points[j].y == points[i].y:
same +=1
else:
t = self.calcK(points[j],points[i])
if t not in k.keys():
k[t] = 1
else:
k[t] += 1
res = max(res, max(k.values())+same)
return res def main():
points = []
points.append(Point(0,0))
points.append(Point(1,1))
points.append(Point(1,-1))
#points.append(Point(0,0))
#points.append(Point(1,1))
#points.append(Point(0,0))
s = Solution()
print s.maxPoints(points) if __name__ == '__main__':
main()
上一篇:编译lua版本问题


下一篇:团队项目7——团队冲刺beta版本目录