LeetCode 题解工作台

找到最接近 0 的数字

给你一个长度为 n 的整数数组 nums ,请你返回 nums 中最 接近 0 的数字。如果有多个答案,请你返回它们中的 最大值 。 示例 1: 输入: nums = [-4,-2,1,4,8] 输出: 1 解释: -4 到 0 的距离为 |-4| = 4 。 -2 到 0 的距离为 |-2| = …

category

1

题型

code_blocks

5

代码语言

hub

3

相关题

当前训练重点

简单 · 数组·driven

bolt

答案摘要

我们定义一个变量 来记录当前最小的距离,初始时 。然后我们遍历数组,对于每个元素 ,我们计算 ,如果 $y \lt d$ 或者 且 $x \gt \textit{ans}$,我们就更新答案 和 。 遍历结束后返回答案即可。

Interview AiBox logo

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

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个长度为 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
lightbulb

解题思路

方法一:一次遍历

我们定义一个变量 d\textit{d} 来记录当前最小的距离,初始时 d=\textit{d}=\infty。然后我们遍历数组,对于每个元素 xx,我们计算 y=xy=|x|,如果 y<dy \lt d 或者 y=dy=dx>ansx \gt \textit{ans},我们就更新答案 ans=x\textit{ans}=xd=y\textit{d}=y

遍历结束后返回答案即可。

时间复杂度 O(n)O(n),其中 nn 是数组的长度。空间复杂度 O(1)O(1)

1
2
3
4
5
6
7
8
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
speed

复杂度分析

指标
时间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
psychology

面试官常问的追问

外企场景
  • 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.

warning

常见陷阱

外企场景
  • 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.

swap_horiz

进阶变体

外企场景
  • 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.

help

常见问题

外企场景

找到最接近 0 的数字题解:数组·driven | LeetCode #2239 简单