LeetCode 题解工作台
访问所有点的最小时间
平面上有 n 个点,点的位置用整数坐标表示 points[i] = [x i , y i ] 。请你计算访问所有这些点需要的 最小时间 (以秒为单位)。 你需要按照下面的规则在平面上移动: 每一秒内,你可以: 沿水平方向移动一个单位长度,或者 沿竖直方向移动一个单位长度,或者 跨过对角线移动 sqr…
3
题型
7
代码语言
3
相关题
当前训练重点
简单 · 数组·数学
答案摘要
对于两个点 $p_1=(x_1, y_1)$ 和 $p_2=(x_2, y_2)$,横坐标和纵坐标分别移动的距离分别为 $d_x = |x_1 - x_2|$ 和 $d_y = |y_1 - y_2|$。 如果 $d_x \ge d_y$,则沿对角线移动 ,再沿水平方向移动 $d_x - d_y$;如果 $d_x < d_y$,则沿对角线移动 ,再沿竖直方向移动 $d_y - d_x$。因此,两个…
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·数学 题型思路
题目描述
平面上有 n 个点,点的位置用整数坐标表示 points[i] = [xi, yi] 。请你计算访问所有这些点需要的 最小时间(以秒为单位)。
你需要按照下面的规则在平面上移动:
- 每一秒内,你可以:
- 沿水平方向移动一个单位长度,或者
- 沿竖直方向移动一个单位长度,或者
- 跨过对角线移动
sqrt(2)个单位长度(可以看作在一秒内向水平和竖直方向各移动一个单位长度)。
- 必须按照数组中出现的顺序来访问这些点。
- 在访问某个点时,可以经过该点后面出现的点,但经过的那些点不算作有效访问。
示例 1:

输入:points = [[1,1],[3,4],[-1,0]] 输出:7 解释:一条最佳的访问路径是: [1,1] -> [2,2] -> [3,3] -> [3,4] -> [2,3] -> [1,2] -> [0,1] -> [-1,0] 从 [1,1] 到 [3,4] 需要 3 秒 从 [3,4] 到 [-1,0] 需要 4 秒 一共需要 7 秒
示例 2:
输入:points = [[3,2],[-2,2]] 输出:5
提示:
points.length == n1 <= n <= 100points[i].length == 2-1000 <= points[i][0], points[i][1] <= 1000
解题思路
方法一:模拟
对于两个点 和 ,横坐标和纵坐标分别移动的距离分别为 和 。
如果 ,则沿对角线移动 ,再沿水平方向移动 ;如果 ,则沿对角线移动 ,再沿竖直方向移动 。因此,两个点之间的最短距离为 。
我们可以遍历所有的点对,计算出每个点对之间的最短距离,然后求和即可。
时间复杂度 ,其中 为点的个数。空间复杂度 。
class Solution:
def minTimeToVisitAllPoints(self, points: List[List[int]]) -> int:
return sum(
max(abs(p1[0] - p2[0]), abs(p1[1] - p2[1])) for p1, p2 in pairwise(points)
)
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(n) since each point pair is visited once. Space complexity is O(1) because no extra data structures proportional to n are used, only scalar accumulators. |
| 空间 | O(1) |
面试官常问的追问
外企场景- question_mark
You may be asked to justify why diagonal moves are always optimal between two points.
- question_mark
Clarify the relationship between horizontal and vertical distances for move counting.
- question_mark
Expect questions linking array iteration with distance calculation, highlighting the Array plus Math pattern.
常见陷阱
外企场景- error
Counting horizontal and vertical moves separately instead of using max(dx, dy) leads to overestimating time.
- error
Ignoring diagonal moves can make solutions longer and fail efficiency expectations.
- error
Off-by-one errors in computing differences between coordinates may cause incorrect totals.
进阶变体
外企场景- arrow_right_alt
Allowing arbitrary order traversal changes the problem into a minimum path or traveling salesman variant.
- arrow_right_alt
Restricting diagonal moves to only certain directions increases complexity and requires conditional logic.
- arrow_right_alt
Expanding to 3D coordinates introduces an extra axis, still solvable with max differences but with three dimensions.