题目:
Given n points on a 2D plane, find the maximum number of
points that lie on the same straight line.
解析:
寻找平面内最多的共线点个数
方法就是穷举法,通过计算共起点的斜率相等来判断共线情况
斜率计算:(y2-y1)/(x2-x1)
注意这里软件计算斜率会有精度问题,所以采用真分数的形式来表达斜率:
1,找到斜率分子分母绝对值的最大公约数
2,分子分母同除以最大公约数
3,为避开除法运算,斜率以字符形式保存
代码:
s和t的最大公约数:
def gcd(s,t):
if t == 0:
return s
else:
return gcd(t,s % t)
同起点直线中,过点数目最多的直线所经过的点数:
def samek(k):
p = 2
for i in range(len(k)):
point = 2
for j in range(i+1,len(k)):
if k[j] == k[i]:
point += 1
if p < point:
p = point
return p
共线点数最多:
def maxpoint(plane):
point = 2
for i in range(len(plane)-1):
start = plane[i]
k =[]
for j in range(i+1,len(plane)):
end = plane[j]
y = end[1]-start[1]
x = end[0]-start[0]
k_gcd = gcd(abs(y),abs(x))
if (y < 0 and x > 0) or (y > 0 and x < 0):
sign = '-'
else:
sign = '+'
k.append(sign + str(abs(y/k_gcd)) + '/' + str(abs(x/k_gcd)))
p = samek(k)
if p > point:
point = p
#print(k,p,point)
return point
运行:
if __name__=='__main__':
a = [[1,1],[1,2],[2,2],[3,3]]
ap = maxpoint(a)
b = [[1,1],[3,2],[5,3],[4,1],[2,3],[1,4]]
bp = maxpoint(b)
print(a,ap)
print(b,bp)