算法分析课每周练习 Max Points on a Line

来源:互联网 发布:布道者软件 编辑:程序博客网 时间:2024/06/05 16:46

关于题目的选取

FIlter By Top Interview Questions依次选取

题目

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.

题目分析

简单暴力的方法是直接计算任意两点间的斜率(考虑垂直的线还有重复的点),两层循环求出结果。

class Point(object):    """Definition for a point."""    def __init__(self, a=0, b=0):        self.x = a        self.y = bclass Solution(object):    def maxPoints(self, points):        """        :type points: List[Point]        :rtype: int        """        n = len(points)          if n < 3:              return n          res = -1          for i in range(n):              k = {'inf': 0}              duplicate = 1              for j in range(n):                  if i == j:                      continue                  elif points[i].x == points[j].x and points[i].y != points[j].y:                      k['inf'] +=1                  elif points[i].x != points[j].x:                      k = 1.0 * (points[j].y - points[i].y) / (points[j].x - points[i].x)                      k[k] = 1 if k not in k.keys() else k[k] + 1                  else:                      duplicate += 1              res = max(res, max(k.values()) + duplicate)          return res  
算法空间复杂度O(n),时间复杂度O(n^2)

算法改进分析

算法实际上计算了两次的某两点间的斜率,因此提高程序的空间占用可以降低运算时间

同一条线上的点的斜率,有些计算应该是冗余的,但是难以减少。


0 0
原创粉丝点击