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

来源:互联网 发布:绝地求生怎么优化fps 编辑:程序博客网 时间:2024/05/20 11:32

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

最开始的方法是两个点 然后计算出直线的系数 然后看哪些点在直线上 ax+b=y 

发现会超时 

后来 如果确定1点 那么只要剩余的点和1组成的斜率相同 它们和1点就在一条直线上 

斜率有两种 普通的 或者直线和x轴垂直 

为了把点1下所有斜率存在一个list方便统计 x轴垂直的斜率设为char'a'

写完之后发现 [ [ 1 , 1 ] , [ 1 , 1 ] , [ 1 , 2 ] ]这个case过不去 

因为[ 1 , 1 ]出现两次 1,2点会被认为是垂直线 1,3 会被认为是一般直线 实际都在一条直线上 

因此多加了一个变量dul 点1固定 之后的点有几个dul 算出来点数都要再加dul (即使所有点都重合也没问题)

固定点1 统计此次最多点数 再更换为固定点2 继续统计 

# Definition for a point.# class Point:#     def __init__(self, a=0, b=0):#         self.x = a#         self.y = bclass Solution:    # @param {Point[]} points    # @return {integer}    def maxPoints(self, points):        start=Point()        end=Point()        length=len(points)        sol=0        #matrix= [([0] * length) for i in range(length)]        if length==0:            return 0        elif length==1:            return 1        elif length==2:            return 2        else:            for i in range(length-1):#(0-7)#                 slope=[]                dul=0                temp=0                for j in range(i+1,length):#(i+1-8)                    start=points[i]                    end=points[j]                    x1=start.x                    y1=start.y                    x2=end.x                    y2=end.y                    if x1==x2 and y1==y2:                        dul=dul+1                    elif x2==x1 and y1!=y2:                        m='a'                        slope.append(m)                    else:                        m=(y2-y1*1.0)/(x2-x1)                        slope.append(m)                                    if slope==[]:                    temp=0                    if temp+dul>sol:                        sol=temp+dul                else:                    for k in slope:                        temp=slope.count(k)                        if temp+dul>sol:                            sol=temp+dul        return sol+1



0 0
原创粉丝点击