LeetCode 题解工作台
找到最接近 0 的数字
给你一个长度为 n 的整数数组 nums ,请你返回 nums 中最 接近 0 的数字。如果有多个答案,请你返回它们中的 最大值 。 示例 1: 输入: nums = [-4,-2,1,4,8] 输出: 1 解释: -4 到 0 的距离为 |-4| = 4 。 -2 到 0 的距离为 |-2| = …
1
题型
5
代码语言
3
相关题
当前训练重点
简单 · 数组·driven
答案摘要
我们定义一个变量 来记录当前最小的距离,初始时 。然后我们遍历数组,对于每个元素 ,我们计算 ,如果 $y \lt d$ 或者 且 $x \gt \textit{ans}$,我们就更新答案 和 。 遍历结束后返回答案即可。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·driven 题型思路
题目描述
给你一个长度为 n 的整数数组 nums ,请你返回 nums 中最 接近 0 的数字。如果有多个答案,请你返回它们中的 最大值 。
示例 1:
输入:nums = [-4,-2,1,4,8] 输出:1 解释: -4 到 0 的距离为 |-4| = 4 。 -2 到 0 的距离为 |-2| = 2 。 1 到 0 的距离为 |1| = 1 。 4 到 0 的距离为 |4| = 4 。 8 到 0 的距离为 |8| = 8 。 所以,数组中距离 0 最近的数字为 1 。
示例 2:
输入:nums = [2,-1,1] 输出:1 解释:1 和 -1 都是距离 0 最近的数字,所以返回较大值 1 。
提示:
1 <= n <= 1000-105 <= nums[i] <= 105
解题思路
方法一:一次遍历
我们定义一个变量 来记录当前最小的距离,初始时 。然后我们遍历数组,对于每个元素 ,我们计算 ,如果 或者 且 ,我们就更新答案 和 。
遍历结束后返回答案即可。
时间复杂度 ,其中 是数组的长度。空间复杂度 。
class Solution:
def findClosestNumber(self, nums: List[int]) -> int:
ans, d = 0, inf
for x in nums:
if (y := abs(x)) < d or (y == d and x > ans):
ans, d = x, y
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(n) since we examine each array element once. Space complexity is O(1) because only a single variable is needed to track the closest number. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Candidate considers edge cases with negative and positive ties.
- question_mark
Candidate directly compares absolute values without extra sorting.
- question_mark
Candidate handles arrays with size 1 or repeated elements correctly.
常见陷阱
外企场景- error
Forgetting to return the larger number in a tie.
- error
Using sorting unnecessarily, increasing time complexity.
- error
Neglecting negative numbers and comparing raw values instead of absolute values.
进阶变体
外企场景- arrow_right_alt
Find the closest number to a given target instead of zero.
- arrow_right_alt
Return all numbers equally closest to zero.
- arrow_right_alt
Handle arrays with floating point numbers instead of integers.