forked from shuboc/LeetCode-2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
max-points-on-a-line.py
45 lines (37 loc) · 1.25 KB
/
max-points-on-a-line.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
from __future__ import print_function
# Time: O(n^2)
# Space: O(n)
#
# Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.
#
import collections
# Definition for a point
class Point:
def __init__(self, a=0, b=0):
self.x = a
self.y = b
class Solution(object):
def maxPoints(self, points):
"""
:type points: List[Point]
:rtype: int
"""
max_points = 0
for i, start in enumerate(points):
slope_count, same = collections.defaultdict(int), 1
for j in xrange(i + 1, len(points)):
end = points[j]
if start.x == end.x and start.y == end.y:
same += 1
else:
slope = float("inf")
if start.x - end.x != 0:
slope = (start.y - end.y) * 1.0 / (start.x - end.x)
slope_count[slope] += 1
current_max = same
for slope in slope_count:
current_max = max(current_max, slope_count[slope] + same)
max_points = max(max_points, current_max)
return max_points
if __name__ == "__main__":
print(Solution().maxPoints([Point(), Point(), Point()]))