LeetCode刷题实战149:直线上最多的点数
Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.
题意
解题
from collections import defaultdict
class Solution:
def maxPoints(self, points):
"""
:type points: List[Point]
:rtype: int
"""
slopes, result = defaultdict(int), 0
for i, point1 in enumerate(points):
slopes.clear()
duplicate = 1
for _, point2 in enumerate(points[i+1:]):
if point1.x == point2.x and point1.y == point2.y:
duplicate += 1
continue
slope = float('inf') if point1.x == point2.x else \
(point1.y - point2.y)/(point1.x - point2.x)
slopes[slope] += 1
if result < duplicate:
result = duplicate
for _, val in slopes.items():
if val + duplicate > result:
result = val + duplicate
return result