首页 > 其他 > 详细

LeetCode 149. Max Points on a Line 多少个点共线

时间:2016-03-13 19:44:12      阅读:213      评论:0      收藏:0      [点我收藏+]

题目: 

  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

 

LeetCode 149. Max Points on a Line 多少个点共线

原文:http://www.cnblogs.com/gufeiyang/p/5272558.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!