LeetCode 题解工作台
直线上最多的点数
给你一个数组 points ,其中 points[i] = [x i , y i ] 表示 X-Y 平面上的一个点。求最多有多少个点在同一条直线上。 示例 1: 输入: points = [[1,1],[2,2],[3,3]] 输出: 3 示例 2: 输入: points = [[1,1],[3,2…
4
题型
5
代码语言
3
相关题
当前训练重点
困难 · 数组·哈希·扫描
答案摘要
我们可以枚举任意两个点 $(x_1, y_1), (x_2, y_2)$,把这两个点连成一条直线,那么此时这条直线上的点的个数就是 2,接下来我们再枚举其他点 $(x_3, y_3)$,判断它们是否在同一条直线上,如果在,那么直线上的点的个数就加 1,如果不在,那么直线上的点的个数不变。找出所有直线上的点的个数的最大值,即为答案。 时间复杂度 ,空间复杂度 。其中 是数组 `points` 的长…
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·哈希·扫描 题型思路
题目描述
给你一个数组 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 <= 300points[i].length == 2-104 <= xi, yi <= 104points中的所有点 互不相同
解题思路
方法一:暴力枚举
我们可以枚举任意两个点 ,把这两个点连成一条直线,那么此时这条直线上的点的个数就是 2,接下来我们再枚举其他点 ,判断它们是否在同一条直线上,如果在,那么直线上的点的个数就加 1,如果不在,那么直线上的点的个数不变。找出所有直线上的点的个数的最大值,即为答案。
时间复杂度 ,空间复杂度 。其中 是数组 points 的长度。
class Solution:
def maxPoints(self, points: List[List[int]]) -> int:
n = len(points)
ans = 1
for i in range(n):
x1, y1 = points[i]
for j in range(i + 1, n):
x2, y2 = points[j]
cnt = 2
for k in range(j + 1, n):
x3, y3 = points[k]
a = (y2 - y1) * (x3 - x1)
b = (y3 - y1) * (x2 - x1)
cnt += a == b
ans = max(ans, cnt)
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Candidate shows a clear understanding of array scanning techniques.
- question_mark
Candidate can efficiently utilize hash tables for counting slopes.
- question_mark
Candidate identifies edge cases, such as vertical lines, and handles them properly.
常见陷阱
外企场景- error
Forgetting to handle vertical lines with an undefined slope.
- error
Incorrectly handling floating-point precision when comparing slopes.
- error
Not using a hash table, leading to a less efficient solution.
进阶变体
外企场景- arrow_right_alt
Consider optimizing the space complexity using different data structures for slope storage.
- arrow_right_alt
Alter the problem to include collinearity checks for points in higher dimensions.
- arrow_right_alt
Allow for duplicate points and adjust the solution to account for them.