找到最接近 0 的数字
难度:
标签:
题目描述
代码结果
运行时间: 27 ms, 内存: 16.1 MB
/*
* Problem: Given an integer array nums of length n, return the number in nums that is closest to 0.
* If there are multiple answers, return the largest number.
*
* Approach using Java Streams:
* 1. Convert the array nums to a stream.
* 2. Use the reduce function to find the number closest to 0.
* 3. The reduce function compares two numbers based on their absolute values.
* 4. If the absolute values are equal, the reduce function keeps the larger number.
* 5. Return the result of the reduction.
*/
public int findClosestNumber(int[] nums) {
return Arrays.stream(nums)
.reduce((a, b) -> Math.abs(a) < Math.abs(b) ? a : Math.abs(a) == Math.abs(b) ? Math.max(a, b) : b)
.orElse(0);
}
解释
方法:
该题解的思路是遍历整数数组 `nums`,寻找与 0 的绝对值距离最小的数字。初始化一个变量 `closest` 为无穷大,用来记录当前找到的最小的绝对距离,以及一个变量 `ans` 来存储这个距离对应的数字值。对于每个数字 `num`,如果 `num` 的绝对值小于 `closest`,则更新 `closest` 和 `ans`。如果 `num` 的绝对值等于当前的 `closest` 但 `num` 比 `ans` 大,则更新 `ans` 以确保在距离相同的情况下返回较大的数。
时间复杂度:
O(n)
空间复杂度:
O(1)
代码细节讲解
🦆
为什么在判断条件中同时检查 abs(num) < closest 和 ans < num,而不是仅仅比较绝对值?
▷🦆
如果所有数字的绝对值都相等,此算法如何确保返回的是所有候选者中的最大值?
▷🦆
当变量 `closest` 的初始值设为无穷大时,这会对算法的性能或结果准确性有什么影响?
▷🦆
在算法中,如果输入数组 `nums` 包含零,输出是否直接就是零,且是否可以提前终止遍历?
▷