程序调试到一点半才搞定····赶快分享出来!!
题目:
Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.
思路:
用二维数组存储斜率,斜率相同并且通过一点的在一条直线上
特殊情况:
斜率不存在时(垂直于X轴)
几个点重合时·····
贴出Python实现代码:
# Definition for a point
# class Point:
# def __init__(self, a=0, b=0):
# self.x = a
# self.y = b
class Solution:
# @param points, a list of Points
# @return an integer
def maxPoints(self, points):
n = len(points)
if n < 3:
return n
result = [0 for i in range(n)]
Slope = [[99 for i in range(n)] for i in range(n) ]
for i in range(n):
for j in range(n):
if i != j:
if points[i].x == points[j].x:
if points[i].y ==points[j].y:
result[i]+=1 #列表 存储有重复的点
Slope[i][j] = 9999+j#+j防止下面统计重复元素最多有多少个时将这个统计上
else:
Slope[i][j] =99999
else:
Slope[i][j] =float((points[i].y - points[j].y))/(points[i].x - points[j].x)
if result[i] == n - 1: #所有点都重合
result[i]-=1 #
result[i] += max([Slope[i].count(Slope[i][j]) for j in range(n)]) -1
if max(result) ==0:
return 2
return max(result)+2