Given an integer array nums
of size n
, return the number with the value closest to 0
in nums
. If there are multiple answers, return the number with the largest value.
Example 1:
Input: nums = [-4,-2,1,4,8] Output: 1 Explanation: The distance from -4 to 0 is |-4| = 4. The distance from -2 to 0 is |-2| = 2. The distance from 1 to 0 is |1| = 1. The distance from 4 to 0 is |4| = 4. The distance from 8 to 0 is |8| = 8. Thus, the closest number to 0 in the array is 1.
Example 2:
Input: nums = [2,-1,1] Output: 1 Explanation: 1 and -1 are both the closest numbers to 0, so 1 being larger is returned.
Constraints:
1 <= n <= 1000
-105 <= nums[i] <= 105
The problem asks us to find the number in a given integer array that is closest to zero. If multiple numbers have the same minimum distance to zero, we should return the largest among them.
The most efficient approach is a single-pass linear scan through the array. We keep track of two variables:
ans
: Stores the current closest number to zero found so far. Initialized to 0.d
: Stores the minimum distance to zero found so far. Initialized to a large value (e.g., infinity
or a very large integer like 1 << 30
to ensure that the first number's distance is smaller).For each number x
in the array, we calculate its absolute value y = |x|
. Then we check if y
is less than d
or if y
is equal to d
but x
is greater than ans
. If either of these conditions is true, it means we've found a closer number or a closer number with a larger value, so we update ans
and d
.
class Solution:
def findClosestNumber(self, nums: List[int]) -> int:
ans, d = 0, float('inf') #Initialize d to infinity
for x in nums:
y = abs(x)
if y < d or (y == d and x > ans):
ans, d = x, y
return ans
ans
and d
.The core logic remains the same across different programming languages. Here are examples in Java, C++, Go and TypeScript:
class Solution {
public int findClosestNumber(int[] nums) {
int ans = 0, d = Integer.MAX_VALUE; // Initialize d to a large value
for (int x : nums) {
int y = Math.abs(x);
if (y < d || (y == d && x > ans)) {
ans = x;
d = y;
}
}
return ans;
}
}
class Solution {
public:
int findClosestNumber(vector<int>& nums) {
int ans = 0, d = INT_MAX; // Initialize d to a large value
for (int x : nums) {
int y = abs(x);
if (y < d || (y == d && x > ans)) {
ans = x;
d = y;
}
}
return ans;
}
};
func findClosestNumber(nums []int) int {
ans, d := 0, math.MaxInt32 // Initialize d to a large value
for _, x := range nums {
y := int(math.Abs(float64(x)))
if y < d || (y == d && x > ans) {
ans, d = x, y
}
}
return ans
}
function findClosestNumber(nums: number[]): number {
let ans = 0;
let d = Infinity; //Initialize d to Infinity
for (const x of nums) {
const y = Math.abs(x);
if (y < d || (y === d && x > ans)) {
ans = x;
d = y;
}
}
return ans;
}
All these implementations achieve the same time and space complexity as the Python version. The only difference is in the syntax and how the large initial value for d
is represented.