思路:
- use exhaustion to find out the longest combinations, here we need 3 loops which is inefficient.
- several nodes have the same K value based on the one node, then they are on the one line.
Here I programed with the second method.
Hash_table is realised by dictionary to deposit the map between k and those nodes.
"""
Definition for a point.
class Point:
def __init__(self, a=0, b=0):
self.x = a
self.y = b
"""
class Solution:
"""
@param: points: an array of point
@return: An integer
"""
def maxPoints(self, points):
# write your code here
if len(points) < 2:
return len(points)
max_all = 1
for i in range(0,len(points)):
max = 1
hash_map = {}
for n in range(0,len(points)):
duplicate = 1
max = 0
k = float("inf")
if n == i:
continue
if points[i] == points[n]:
duplicate += 1
continue
# k is infinite
if points[i].x == points[n].x:
if k in hash_map:
hash_map[k].append(points[n])
else:
hash_map[k] = [points[n]]
# k is finite
else:
k = (points[i].y - points[n].y) / (points[i].x - points[n].x)
if k in hash_map:
hash_map[k].append(points[n])
else:
hash_map[k] = [points[n]]
max_list = hash_map.values()
for i in max_list:
if max < len(i) + duplicate:
max = len(i) + duplicate
if max > max_all:
max_all = max
return max_all
Here is a confusion that the "==" is used to compare two instances(points[i] == points[n]), which is not that accurate as instances ought to have diverse Id in Ram.











网友评论