LeetCode 题解工作台
缀点成线
给定一个整数数组 coordinates ,其中 coordinates[i] = [x, y] , [x, y] 表示横坐标为 x 、纵坐标为 y 的点。请你来判断,这些点是否在该坐标系中属于同一条直线上。 示例 1: 输入: coordinates = [[1,2],[2,3],[3,4],[4…
3
题型
4
代码语言
3
相关题
当前训练重点
简单 · 数组·数学
答案摘要
时间复杂度 ,其中 表示 `coordinates` 数组的长度。空间复杂度 。 class Solution:
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·数学 题型思路
题目描述
给定一个整数数组 coordinates ,其中 coordinates[i] = [x, y] , [x, y] 表示横坐标为 x、纵坐标为 y 的点。请你来判断,这些点是否在该坐标系中属于同一条直线上。
示例 1:

输入:coordinates = [[1,2],[2,3],[3,4],[4,5],[5,6],[6,7]] 输出:true
示例 2:

输入:coordinates = [[1,1],[2,2],[3,4],[4,5],[5,6],[7,7]] 输出:false
提示:
2 <= coordinates.length <= 1000coordinates[i].length == 2-104 <= coordinates[i][0], coordinates[i][1] <= 104coordinates中不含重复的点
解题思路
方法一:数学
时间复杂度 ,其中 表示 coordinates 数组的长度。空间复杂度 。
class Solution:
def checkStraightLine(self, coordinates: List[List[int]]) -> bool:
x1, y1 = coordinates[0]
x2, y2 = coordinates[1]
for x, y in coordinates[2:]:
if (x - x1) * (y2 - y1) != (y - y1) * (x2 - x1):
return False
return True
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Candidate uses efficient math methods like slope or cross product to solve the problem.
- question_mark
The solution handles edge cases, especially when there are only two points.
- question_mark
Candidate explains the approach clearly, demonstrating understanding of geometry and array handling.
常见陷阱
外企场景- error
Overlooking the edge case of two points, which should always return true.
- error
Using division to calculate slopes, which can lead to precision issues or division by zero.
- error
Failing to consider all points in the array when checking for collinearity.
进阶变体
外企场景- arrow_right_alt
Modify the problem to check for a straight line in 3D space using an additional z-coordinate.
- arrow_right_alt
Ask the candidate to find if the points form a curve or parabola instead of a straight line.
- arrow_right_alt
Extend the problem to handle multiple line segments and check if they form a continuous straight line.