LeetCodeDiary

A Diary for solving LeetCode problems

View on GitHub

149. 直线上最多的点数

给你一个数组 points ,其中 points[i] = [xi, yi] 表示 X-Y 平面上的一个点。求最多有多少个点在同一条直线上。

示例 1:

img

输入:points = [[1,1],[2,2],[3,3]]
输出:3

示例 2:

img

输入:points = [[1,1],[3,2],[5,3],[4,1],[2,3],[1,4]]
输出:4

提示:

哈希表 困难

代码

class Solution:
    def maxPoints(self, points: List[List[int]]) -> int:
        ans = 1
        n = len(points)
        for i in range(n-1):
            counter = Counter()
            for j in range(i+1,n):
                dx, dy = points[i][0] - points[j][0], points[i][1] - points[j][1]
                counter[dy/dx if dx else 'inf'] += 1
            ans = max(ans,max(counter.values())+1)
        return ans