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

思路:

  这道题目并不难。暴力枚举其它点与当前点的斜率。 复杂度为 O(n^2).

  可能是由于时间久没刷题的原因。有一个异常没考虑。 就是重点。 除此之外,斜率给无穷也需要考虑。 以下是代码。

# 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
        """
        n = len(points)
        if n==0: return 0
        ans = 1
        for i in xrange(n):
            dic = {}
            inf = []
            temp = 1
            for j in xrange(n):
                if i==j:continue
                if points[i].x == points[j].x and points[i].y == points[j].y:
                    temp += 1
                    continue
                if points[i].x == points[j].x:
                    inf.append(j)
                else :
                    value = 1.0*(points[i].y - points[j].y)/(points[i].x - points[j].x)
                    if dic.has_key(value):
                        dic[value].append(j)
                    else:
                        dic[value] = [j]
        
            for key in dic.keys():
                ans = max(ans, len(dic[key]) + temp)
            ans = max(ans, len(inf) + temp)
        
        return ans
View Code

 

posted @ 2016-03-13 17:29  Gu Feiyang  阅读(183)  评论(0)    收藏  举报