Skip to content
The Chat Archive
gpt-4.1-mini-2025-04-14· OpenAI LMArena Human Preference 140K

给你一个长度为 n 的整数数组 nums ,请你返回 nums 中最 接近 0 的数字。如果有多个答案,请你返回它们中的 最大值 。 class Solution: def…

  1. User

    给你一个长度为 n 的整数数组 nums ,请你返回 nums 中最 接近 0 的数字。如果有多个答案,请你返回它们中的 最大值 。

    class Solution: def findClosestNumber(self, nums: List[int]) -> int:

  2. Assistant

    你这个题目是让找数组中最接近 0 的数字,如果有多个数字距离 0 一样近,则返回其中的最大值。

    思路:

    • 遍历数组,记录当前最接近 0 的数字 closest
    • 对比时,先比较绝对值,绝对值小的更新
    • 如果绝对值相等,则取较大的那个数字

    代码实现如下:

    from typing import List
    
    class Solution:
        def findClosestNumber(self, nums: List[int]) -> int:
            closest = nums[0]
            for num in nums:
                if abs(num) < abs(closest):
                    closest = num
                elif abs(num) == abs(closest) and num > closest:
                    closest = num
            return closest
    

    这样就能满足题目要求。

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.