Leetcode-Solutions icon indicating copy to clipboard operation
Leetcode-Solutions copied to clipboard

Find Closest Number to Zero

Open Revamth opened this issue 1 year ago • 3 comments

#include <vector>
#include <cmath>
#include <algorithm>

class Solution {
public:
    int findClosestNumber(const std::vector<int>& nums) {
        int closest = nums[0];
        
        for (int x : nums) {
            if (std::abs(x) < std::abs(closest)) {
                closest = x;
            }
        }
        
        if (closest < 0 && std::find(nums.begin(), nums.end(), std::abs(closest)) != nums.end()) {
            return std::abs(closest);
        } else {
            return closest;
        }
    }
};

The solution which you have provided has a time complexity of O(2n) in the worst case.

Instead of using the std::find function call we can simply keep track whether the minimum value we are getting is coming from negative value and positive value and update answer accordingly.

My code is provided here. Please verify it:

class Solution
{
    public:
        int findClosestNumber(vector<int> &nums)
        {
            int n = nums.size();
            int ans = INT_MAX;
            bool val = false;
            for (int i = 0; i < n; i++)
            {
                if (nums[i] > 0)
                {
                    if (nums[i] <= ans)
                    {
                        ans = nums[i];
                        val = true;
                    }
                }
                else
                {
                    int num = -nums[i];
                    if (num < ans)
                    {
                        ans = num;
                        val = false;
                    }
                }
            }
            if (val == false) return -ans;
            else return ans;
        }
};

Revamth avatar Sep 17 '24 23:09 Revamth

Yes, same for the js too, we can check the max element in the same for loop instead of using include() function which takes O(n) time complexity.

Mayur-666 avatar Sep 29 '24 03:09 Mayur-666

Javascript: without includes. O(n)

var findClosestNumber = function (nums) {
  let closest = nums[0];

  for (let i = 1; i < nums.length; i++) {
    if (
      Math.abs(nums[i]) < Math.abs(closest) ||
      (Math.abs(nums[i]) === Math.abs(closest) && nums[i] > closest)
    ) {
      closest = nums[i];
    }
  }

  return closest;
}

powerrampage avatar Oct 02 '24 11:10 powerrampage

Javascript: without includes. O(n)

var findClosestNumber = function (nums) { let closest = nums[0];

for (let i = 1; i < nums.length; i++) { if ( Math.abs(nums[i]) < Math.abs(closest) || (Math.abs(nums[i]) === Math.abs(closest) && nums[i] > closest) ) { closest = nums[i]; } }

return closest; }

I agree

maheshmuttintidev avatar Jan 28 '25 06:01 maheshmuttintidev