您的位置:首页 > 编程语言

[LeetCode]149. Max Points on a Line 深入浅出讲解和代码示例

2017-07-13 14:23 453 查看

1、汇总概要

以下思路涵盖了哈希、数学计算等知识点

2、题目

Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.

3、审题

给定一堆2D空间的点,求取可落于一条直线的最多点。

4、解题思路

1) 数学计算建模

因两点成一直线,所以从判断三个点落于一条直线开始建模。

直线公式:ax +by +c = 0 => 则(a,b,c)中(x参数,y参数, 偏移量)可唯一决定一条直线(两个参数即可,但考虑到有平行于x轴、y轴等特例情况)

由任意两点,可计算出参数:

a = (y2-y1)/(x2-x1)

c = y1 - a * x1

=>(a,b,c) = ((y2-y1)/(x2-x1), -1, y1-a*x1)

考虑特例:1) 直线平行于x轴(y1=y2)时:(a,b,c) = (0,1,-y1)

  2) 直线平行于y轴(x1=x2)时:(a,b,c) = (1,0,-x1)

2) 用hash表来存放"点”以及对应的直线参数

key = (a,b,c)

value = [point1, point2, point3...] 即所有直线参数相同的点,遍历完毕后value最多的,即为结果。



5、代码示例 - Python

import time
class point:
def __init__(self,x,y):
self.x = x
self.y = y

class Solution():
def getdis(self,p1,p2):
dis = [0,0,0]
ydis = p2.y - p1.y
xdis = p2.x - p1.x
if xdis == 0:
dis=[1.0,0.0,-p1.x]
else:
if ydis == 0:
dis = [0.0,1.0,-p1.y]
else:
a = ydis/xdis
c = p1.y - a*p1.x
dis = [a,-1.0,c]
tdis = (dis[0],dis[1],dis[2])
return tdis

def maxPoints(self,points):
maxnum = 2
maxvalue = ["1","2"]
dict = {}
leng = len(points)
for i in range(0,leng):
for j in range(i+1,leng):
p1 = points[i]
p2 = points[j]
tdis = self.getdis(p1,p2)
if dict.has_key(tdis): #exit in dict -> extend the dict
strj = str(j)
if strj not in dict[tdis]:
dict[tdis].extend(str(j))
curlen = len(dict[tdis])
if curlen > maxnum:
maxnum = curlen
maxvalue = dict[tdis]
else: # not exist in dict, insert
dict[tdis] = [str(i),str(j)]
return dict

if __name__ == "__main__":
num = 6
points = [0 for i in range(num)]
print "points: ", points
p1 = point(1.0,1.0)
p2 = point(2.0,2.0)
p3 = point(1.0,2.0)
p4 = point(2.0,4.0)
p5 = point(4.0,7.0)
p6 = point(4.0,8.0)
p7 = point(1.5,3.0)
p8 = point(5.0,5.0)
p9 = point(0.5,0.5)
p10 = point(2.5,2.5)
points = [p1,p2,p3,p4,p5,p6,p7,p8,p9,p10]

st = Solution()
st.maxPoints(points)


---------------------------------------------------------------------------------------------------
本文链接:http://blog.csdn.net/karen0310/article/details/75053593
请尊重作者的劳动成果,转载请注明出处!

---------------------------------------------------------------------------------------------------
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息