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

来源:互联网 发布:如何摆脱网络成瘾 编辑:程序博客网 时间:2024/05/02 01:07

题目描述

给出二维平面上的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 = bclass 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)

阅读全文
0 0
原创粉丝点击