【LetMeFly】2239.找到最接近 0 的数字:遍历 力扣题目链接:https://leetcode.cn/problems/find-closest-number-to-zero/ 
给你一个长度为 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  
 
    
解题方法:遍历 使用变量ans记录当前的最优答案,初始值为nums[0]。
遍历nums数组,对于其中元素t,若以下则说明t比ans更优,更新ans为t:
abs(t) < abs(ans) 
abs(t) == abs(ans)且ans < 0 
 
最终返回ans。
时间复杂度$O(len(nums))$ 
空间复杂度$O(1)$ 
 
AC代码 C++ 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 class  Solution  {public :     int  findClosestNumber (vector<int >& nums)   {         int  ans = nums[0 ];         for  (int  t : nums) {             if  (abs (t) < abs (ans) || abs (t) == abs (ans) && ans < 0 ) {                 ans = t;             }         }         return  ans;     } };
 
Python 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 ''' Author: LetMeFly Date: 2025-01-20 13:31:49 LastEditors: LetMeFly.xyz LastEditTime: 2025-01-20 13:32:00 ''' from  typing import  List class  Solution :     def  findClosestNumber (self, nums: List [int ] ) -> int :         ans = nums[0 ]         for  t in  nums:             if  abs (t) < abs (ans) or  abs (t) == abs (ans) and  ans < 0 :                 ans = t         return  ans
 
Java 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 class  Solution  {     public  int  findClosestNumber (int [] nums)  {         int  ans  =  nums[0 ];         for  (int  t : nums) {             if  (Math.abs(t) < Math.abs(ans) || Math.abs(t) == Math.abs(ans) && ans < 0 ) {                 ans = t;             }         }         return  ans;     } }
 
Go 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 package  mainfunc  abs (a int )   int  {     if  a < 0  {         return  -a     }     return  a }func  findClosestNumber (nums []int )   int  {     ans := nums[0 ]     for  _, t := range  nums {         if  abs(t) < abs(ans) || abs(t) == abs(ans) && ans < 0  {             ans = t         }     }     return  ans }
 
同步发文于CSDN和我的个人博客 ,原创不易,转载经作者同意后请附上原文链接 哦~
Tisfy:https://letmefly.blog.csdn.net/article/details/145264674