给你一个长度为
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 。
思路分析:
找出数组 nums 里面绝对值最小的元素的最大值即可。
代码实现:
class Solution {
public int findClosestNumber(int[] nums) {
int res = nums[0];
for(int n : nums) {
if(Math.abs(n)==Math.abs(res))
res=Math.max(n,res);
else if(Math.abs(n)<Math.abs(res))
res=n;
}
return res;
}
}
提交结果:
执行结果:
通过
执行用时:2 ms, 在所有 Java 提交中击败了82.15%的用户
内存消耗:42 MB, 在所有 Java 提交中击败了5.10%的用户
通过测试用例:227 / 227