Given an integer array nums, return the number with the smallest absolute value. If there is a tie, return the positive number.
nums = [-4,-2,1,4,8]1nums = [2,-1,1]1ans = nums[0]|nums[i]||nums[i]| < |ans|: update ans = nums[i]|nums[i]| == |ans| and nums[i] > 0: ans = nums[i] (tie → positive)Distance from zero = absolute value. We keep the element with the smallest |value| seen so far. Tie-breaking: both -x and x have the same distance, but we must return the positive one, so we update when we see a positive tie.
Sorting by distance would work, but costs O(n log n). One pass that keeps the best answer so far is enough.
Compare distances using the absolute value. Replace the best if a number is strictly closer. If the distance is equal, keep the larger number.
Closest to zero means the smallest absolute value. Always handle the tie rule explicitly: equal distance, keep the larger number.
Run the animation above on your own input, or watch the 1:15 video explanation of Find Closest Number to Zero with a dry run and Java code.