Home > Back-end >  Find Closest Number to Zero
Find Closest Number to Zero

Time:07-23

I used this approach but it is not working on input like [1,1,-1].When ever -1 comes after 1 in arrays it is showing wrong answer.

Problem statement to the question is 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.

class Solution {
    public int findClosestNumber(int[] nums) {
        int minDiff=Integer.MAX_VALUE;
        int ans=0;
        for(int i=0;i<nums.length;i  )
        {
            if(Math.abs(nums[i])<minDiff)
            {
                minDiff=Math.abs(nums[i]);
                ans=i;
            }else if(Math.abs(nums[i])==minDiff)
            {
                ans=Math.max(ans,i);
            }
        }
        return nums[ans];
    }
}

CodePudding user response:

Just update the else if condition:

else if(Math.abs(nums[i])==minDiff)
{
    ans=Math.max(ans,i);
}

like this:

     else if(Math.abs(nums[i])==minDiff)
     {
          ans=nums[ans] > nums[i] ? ans : i;
     }

compare the value at indexes, rather than comparing indexes.

  • Related