zoukankan      html  css  js  c++  java
  • 边工作边刷题:70天一遍leetcode: day 7

    Max Points on a Line

    要点:这题暴力解是用任何两点确定一条直线,然后对其他点检查是否共线,显然,这里没用空间来存储之前的检查结果,所以time complexity是O(n3)。这题的难点是如何存储从而实现O(n2)解。思路是另一种确定一条直线的方法是一点和theta,所以theta可以作为map的key。每次内循环就是检查对于该点下最多共线的点数。
    错误点:

    • 双循环loop所有pair的方法,inner loop要找外层index的下一个
    • hashmap是local的,不是global的
    • localmax=1: 这样1个点或者都是相同点可以pass
    • theta的计算:对于java,因为坐标是int,必须先用(double) cast,及时theta类型是double。而python没有类型,用float(x-x0)即可
    # 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
            """
            maxp = 0
            for i in range(len(points)):
                localmax = 1
                hmap = {}
                x,y = points[i].x,points[i].y
                same = 0
                for j in range(i+1, len(points)):
                    px,py = points[j].x,points[j].y
                    if px-x==0:
                        if py==y:
                            same+=1
                            continue
                        else:
                            theta = float("inf")
                    else:
                        theta = (py-y)/float(px-x)
                    print i,j, theta
                    if theta not in hmap:
                        hmap[theta]=2
                    else:
                        hmap[theta]+=1
                    if hmap[theta]>localmax:
                        localmax = hmap[theta]
                if localmax+same>maxp:
                    maxp = localmax+same
            return maxp
                    
    
    
  • 相关阅读:
    调用 验证码
    始终居中的弹出层
    jq常用
    ThinkPHP redirect 方法
    session 的生成和删除
    1355:字符串匹配问题(strs)
    1348:【例49】城市公交网建设问题
    1357:车厢调度(train)
    1358:中缀表达式值(expr)
    1351:【例412】家谱树
  • 原文地址:https://www.cnblogs.com/absolute/p/5560412.html
Copyright © 2011-2022 走看看