LeetCode 题解工作台

找到最近的人

给你三个整数 x 、 y 和 z ,表示数轴上三个人的位置: x 是第 1 个人的位置。 y 是第 2 个人的位置。 z 是第 3 个人的位置,第 3 个人 不会移动 。 第 1 个人和第 2 个人以 相同 的速度向第 3 个人移动。 判断谁会 先 到达第 3 个人的位置: 如果第 1 个人先到达,…

category

1

题型

code_blocks

8

代码语言

hub

3

相关题

当前训练重点

简单 · 数学·driven

bolt

答案摘要

我们计算出第 个人和第 个人的距离 ,第 个人和第 个人的距离 。 - 如果 $a = b$,说明两个人同时到达,返回 ;

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 数学·driven 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你三个整数 xyz,表示数轴上三个人的位置:

  • x 是第 1 个人的位置。
  • y 是第 2 个人的位置。
  • z 是第 3 个人的位置,第 3 个人 不会移动 

第 1 个人和第 2 个人以 相同 的速度向第 3 个人移动。

判断谁会 先 到达第 3 个人的位置:

  • 如果第 1 个人先到达,返回 1 。
  • 如果第 2 个人先到达,返回 2 。
  • 如果两个人同时到达,返回

根据上述规则返回结果。

 

示例 1:

输入: x = 2, y = 7, z = 4

输出: 1

解释:

  • 第 1 个人在位置 2,到达第 3 个人(位置 4)需要 2 步。
  • 第 2 个人在位置 7,到达第 3 个人需要 3 步。

由于第 1 个人先到达,所以输出为 1。

示例 2:

输入: x = 2, y = 5, z = 6

输出: 2

解释:

  • 第 1 个人在位置 2,到达第 3 个人(位置 6)需要 4 步。
  • 第 2 个人在位置 5,到达第 3 个人需要 1 步。

由于第 2 个人先到达,所以输出为 2。

示例 3:

输入: x = 1, y = 5, z = 3

输出: 0

解释:

  • 第 1 个人在位置 1,到达第 3 个人(位置 3)需要 2 步。
  • 第 2 个人在位置 5,到达第 3 个人需要 2 步。

由于两个人同时到达,所以输出为 0。

 

提示:

  • 1 <= x, y, z <= 100
lightbulb

解题思路

方法一:数学

我们计算出第 11 个人和第 33 个人的距离 aa,第 22 个人和第 33 个人的距离 bb

  • 如果 a=ba = b,说明两个人同时到达,返回 00
  • 如果 a<ba \lt b,说明第 11 个人会先到达,返回 11
  • 否则,说明第 22 个人会先到达,返回 22

时间复杂度 O(1)O(1),空间复杂度 O(1)O(1)

1
2
3
4
5
6
class Solution:
    def findClosest(self, x: int, y: int, z: int) -> int:
        a = abs(x - z)
        b = abs(y - z)
        return 0 if a == b else (1 if a < b else 2)
speed

复杂度分析

指标
时间complexity is O(1) because distance calculation and comparison involve only basic arithmetic. Space complexity is O(1) since no extra storage beyond a few variables is needed.
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    The problem expects a direct math-driven approach rather than iterative simulation.

  • question_mark

    Watch for off-by-one errors when calculating distances along the number line.

  • question_mark

    Clarify handling of ties to avoid ambiguous return values.

warning

常见陷阱

外企场景
  • error

    Ignoring absolute value when calculating distances can lead to incorrect results.

  • error

    Assuming Person 1 is always closer without proper comparison.

  • error

    Returning wrong values in tie scenarios instead of zero.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Adding multiple people approaching the same target requires selecting the minimum distance among all.

  • arrow_right_alt

    Changing the number line to a 2D grid requires Euclidean distance comparison.

  • arrow_right_alt

    Introducing variable speeds adds a weighting factor to distance calculations.

help

常见问题

外企场景

找到最近的人题解:数学·driven | LeetCode #3516 简单