Find Closest Number to Zero
#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;
}
};
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.
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;
}
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