您的位置:首页 > 编程语言 > Python开发

[LintCode 186] 最多有多少个点在一条直线上(Python)

2017-09-05 14:19 411 查看

题目描述

给出二维平面上的n个点,求最多有多少点在同一条直线上。

样例

给出4个点:(1, 2), (3, 6), (0, 0), (1, 3)。

思路

借助辅助二维数组,存储每两点之间的斜率和截距。

代码

# Definition for a point.
# class Point:
#     def __init__(self, a=0, b=0):
#         self.x = a
#         self.y = b

class Solution:
# @param {int[]} points an array of point
# @return {int} an integer
def maxPoints(self, points):
# Write your code here
if points is None or len(points) == 0:
return 0
if len(points) == 1:
return 1
tmp = [[None for col in range(len(points))] for raw in range(len(points))]
for i in range(len(points)):
for j in range(len(points)):
if i != j:
if points[i].y - points[j].y != 0:
k = float(points[i].x - points[j].x)/float(points[i].y - points[j].y)
b = points[i].y - k * points[i].x
tmp[i][j] = (k, b)
elif points[i].y == points[j].y and points[i].x == points[j].x:
tmp[i][j] = (0, 0)
res = 2
for raw in tmp:
t = 0
for i in set(raw):
if i is not None:
t = max(t, raw.count(i))
t += 1
res = max(res, t)
return res


复杂度分析

时间复杂度O(n2),空间复杂度O(n2)。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: