您的位置:首页 > 其它

[LeetCode]149. Max Points on a Line

2016-11-13 23:18 387 查看

0. 问题地址

https://leetcode.com/problems/max-points-on-a-line/

1. 问题简述

给定n个二位坐标点,求最多的处于同一直线的点的个数

2. 解题思路

暴力。O(n*n*log(n)),记录所有点对的斜率(横坐标相同的话记为inf),记录对于一个点。求得包含此点的点对斜率出现的频次最大值,最终求得结果。

3. 题解代码

class Point(object):
def __init__(self, a=0, b=0):
self.x = a
self.y = b

def get_slope(a, b):
if a.x == b.x:
return float('inf')
return float(a.y - b.y) / (a.x - b.x)

class Solution(object):
def maxPoints(self, points):
"""
:type points: List[Point]
:rtype: int
"""
size = len(points) # size(len) of points
if size <= 2: return size
pos = [1 for _ in points] # every position with same initial value 1

# handle same coordinates(same position)
for i in range(0, size):
if pos[i] == 0: continue

for j in range(i + 1, size):
if points[i].x == points[j].x and points[i].y == points[j].y:
pos[i] += 1
pos[j] = 0 # mark idx [j] to 0

ans = max(pos)
for i in range(0, size):
if pos[i] == 0: continue

slope_dict = {}
for j in range(i + 1, size):
if pos[j] == 0: continue

slope = get_slope(points[i], points[j])
# print "(", points[i].x, ",", points[i].y, ")", "(", points[j].x, ",", points[j].y, ")", slope
if slope in slope_dict:
slope_dict[slope] += pos[j]
else:
slope_dict[slope] = pos[i] + pos[j]

if slope_dict == {}: continue

# print slope_dict
ans = max(ans, max(slope_dict.values()))

return ans

if __name__ == '__main__':

sol = Solution()
points = [Point(84,250),
Point(0,0),
Point(1,0),
Point(0,-70),
Point(0,-70),
Point(1,-1),
Point(21,10),
Point(42,90),
Point(1, 1),
Point(-42,-230),
]
print sol.maxPoints(points), "is answer"
# [[84,250],[0,0],[1,0],[0,-70],[0,-70],[1,-1],[21,10],[42,90],[-42,-230]]
# 6 is answer

4. 速度

按理说这个做法很笨,甚至有超时可能,但是看了结果却发现是在python中最快的。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: