leetcode149. 直线上最多的点数

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sinat_36811967/article/details/88846331

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

示例 1:
输入: [[1,1],[2,2],[3,3]]
输出: 3
示例 2:
输入: [[1,1],[3,2],[5,3],[4,1],[2,3],[1,4]]
输出: 4

O(N²)的方法,建立一个记录斜率的字典,注意要有个记录重复点的参数,最后计算斜率的时候要提升精度用到Decimal:

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

class Solution:
    def maxPoints(self, points: List[Point]) -> int:
        res = 0
        for i, point1 in enumerate(points):
            oneline_dict, same = {}, 1  # 斜率字典,相同点个数
            for j, point2 in enumerate(points[i+1:]):
                if point1.x == point2.x and point1.y == point2.y:
                    same += 1
                    continue
                from decimal import Decimal  # 提高精度
                oneline = float('inf') if point1.x == point2.x\
                    else Decimal(point2.y-point1.y)/Decimal(point2.x-point1.x)
                oneline_dict[oneline] = oneline_dict.get(oneline, 0) + 1
            if res < same:
                res = same
            for k, v in oneline_dict.items():
                if v+same > res:
                    res = v+same
        return res

猜你喜欢

转载自blog.csdn.net/sinat_36811967/article/details/88846331