题目描述
给你一个数组 points ,其中 points[i] = [xi, yi] 表示 X-Y 平面上的一个点。求最多有多少个点在同一条直线上。
示例 1:
输入:points = [[1,1],[2,2],[3,3]]
输出:3
示例 2:
提示:
输入:points = [[1,1],[3,2],[5,3],[4,1],[2,3],[1,4]]
输出:4
1 <= points.length <= 300
points[i].length == 2
-104 <= xi, yi <= 104
points 中的所有点 互不相同
解题思路
首先思考一个问题,在同一直线上的条件是什么?
直线上的每个点连成的直线斜率相等
我们进行一次双层遍历,外层遍历整个点数组,内层遍历外层点位置之后的点数组,通过求斜率的公式,构建一个哈希表,将斜率出现的次数记录在表中,内层遍历结束后,找到出现次数最多的斜率,这就是外层点位置为首的直线最多的点的个数(+1)。
代码
贴一下leetcode通过代码
class Solution:
def maxPoints(self, points: List[List[int]]) -> int:
answer=0
for i in range(len(points)):
temp_dict=dict()
for j in range(i+1,len(points)):
if (points[j][0]-points[i][0])==0:
temp="*"
else:
temp=(points[j][1]-points[i][1])/(points[j][0]-points[i][0])
if temp not in temp_dict:
temp_dict[temp]=1
else:
temp_dict[temp]+=1
if len(temp_dict)!=0:
b=max(temp_dict.values())
answer=max(b,answer)
return answer+1