LeetCode 2239: Find Closest Number to Zero

Array

Problem Description

Explanation

To find the number closest to zero in the given array, we iterate through the array and keep track of the number with the smallest absolute value. If there are multiple numbers with the same absolute value, we return the number with the largest value. We can achieve this by comparing the absolute values and updating the closest number and keeping track of the largest number seen so far.

  • Start by initializing variables closestNumber and largestNumber to the first element of the array.
  • Iterate through the array, updating closestNumber and largestNumber based on the absolute values and values of the current element.
  • Return the closestNumber as the result.

The time complexity of this solution is O(n) where n is the number of elements in the array. The space complexity is O(1).

Solutions

public int findClosestToZero(int[] nums) {
    int closestNumber = nums[0];
    int largestNumber = nums[0];
    
    for (int i = 1; i < nums.length; i++) {
        if (Math.abs(nums[i]) < Math.abs(closestNumber) || (Math.abs(nums[i]) == Math.abs(closestNumber) && nums[i] > closestNumber)) {
            closestNumber = nums[i];
            largestNumber = Math.max(largestNumber, nums[i]);
        }
    }
    
    return closestNumber;
}

Loading editor...