算法分析课每周练习 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
- 算法分析课每周练习 Max Points on a Line
- Max Points on a Line
- Max Points on a Line
- Max Points on a Line
- Max Points on a Line
- Max Points on a Line
- Max Points on a Line
- Max Points On a Line
- Max Points on a Line
- Max Points on a Line
- Max Points on a Line
- max points on a line
- Max Points on a Line
- Max Points on a Line
- Max Points on a Line
- Max Points on a Line
- Max Points on a Line
- Max Points on a Line
- UVa 12096 The SetStack Computer 【STL】【stack】
- rt2860v2源码分析三
- unity客户端
- ASP.NET MVC中使用Log4Net
- Android AsyncTask使用详解
- 算法分析课每周练习 Max Points on a Line
- [LeetCode] 91. Decode Ways
- ant使用
- nginx启用brotli压缩算法
- 文章标题
- 关于并行计算的一些名词
- jackjson实现javabean转换为json
- 1.2.4 Box of Bricks
- CSS3选择器