Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Find Closest Number to Zero #19

Open
Revamth opened this issue Sep 17, 2024 · 2 comments
Open

Find Closest Number to Zero #19

Revamth opened this issue Sep 17, 2024 · 2 comments

Comments

@Revamth
Copy link

Revamth commented Sep 17, 2024

#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;
        }
};
@Mayur-666
Copy link

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.

@powerrampage
Copy link

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;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants