题目 https://oj.leetcode.com/problems/max-points-on-a-line/

 

答案与分析 http://www.aiweibang.com/yuedu/183264.html

     http://blog.csdn.net/ojshilu/article/details/21618675

     http://www.1point3acres.com/bbs/thread-14425-1-1.html

       http://akalius.iteye.com/blog/161852

       http://jchu.blog.sohu.com/116744856.html

       https://oj.leetcode.com/discuss/7607/accepted-code-in-python

下面是我的解法,跟http://blog.csdn.net/ojshilu/article/details/21618675 的解法是类似的,

主要思想是:1)选去平面上任意的两个点 2) 计算剩下的点会在之前两点决定的线上会有多少个3)记录最大值

我自己试了试少量的点,算法上是正确的,但是提交到leetcode就TLE(Time Limit Exceeded)了,但是上面那个链接上的用的是c++就通过了。。。。

那就只好学习下leetcode上AC的python代码了(感觉还是国内博客上的代码好懂。。。)

这个是我自己的代码

# 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 maxPoints(self, points):
        
        max_num = 2
        
        if len(points)<3:
            return len(points)
        
        for a in points:
            for b in points[1:]:
                sums = 2
                if b.x == a.x and b.y == a.y:
                    continue
                
                for c in points:
                    if c.x !=a.x and c.x != b.x\
                    and c.y!=a.y and c.y != b.y\
                    and (c.y-a.y)*(b.x-a.x) == (b.y-a.y)*(c.x-a.x):#(c.y-a.y)/(c.x-a.x) == (b.y-a.y)/(b.x-a.x)
                        sums = sums +1
                        
                if max_num < sums :
                    max_num =sums
        
        return max_num
    
points = []
points.append(Point(40,-20))
points.append(Point(4,-2))
points.append(Point(8,-4))
points.append(Point(50,-17))

print points

c = Solution()
a = c.maxPoints(points)

print a

 

posted on 2014-08-06 22:19  混沌奇迹  阅读(562)  评论(0编辑  收藏  举报