149 直线上最多的点数(Leetcode)

149 直线上最多的点数

editorial:

固定一个点,计算其他点到达该点的斜率,然后输出相同斜率个数最大值+1。判断好边界条件(一个点的情况,直接输出1)。而斜率采用向量(x, y)的形式,保证该向量gcd(x, y)=1,然后对于x,y同号,都转成正数;异号,保证x为正数,y为负数。(O(n^2log(n)))

code:

class Solution:
    def maxPoints(self, points: List[List[int]]) -> int:
        import math
        if(len(points) == 1):
            return 1
        ans = 0
        for i in range(len(points)):
            map_dict = {}
            for j in range(len(points)):
                if i == j:
                    continue
                x, y = points[i][0] - points[j][0], points[i][1] - points[j][1]
                x_y_gcd = math.gcd(abs(x), abs(y))
                if (x > 0 and y > 0) or (x < 0 and y < 0):
                    x, y = abs(x), abs(y)
                elif x < 0 and y > 0:
                    x, y = -x, -y
                x //= x_y_gcd
                y //= x_y_gcd
                map_dict[(x, y)] = map_dict.get((x, y), 0) + 1
            ans = max(ans-1, *map_dict.values())+1
        return ans    
原文地址:https://www.cnblogs.com/lemon-jade/p/14624165.html