Leetcode 2239. Find Closest Number to Zero
Given an integer array nums
of size n
, return the number with the value closest to zero. If there are multiple answers, return the number with the largest value.
Q: What is the range of values that can be in nums
?
A: Values can be within the range of standard 32-bit integers, i.e., -2^31
to 2^31 - 1
.
Q: What is the size range for the array nums
?
A: The size of the array nums
can vary from 1 to 10^4
.
Q: Can the array contain duplicate values? A: Yes, the array can contain duplicate values.
Q: Is the array always non-empty? A: Yes, according to the problem constraints, the array will always contain at least one number.
Initialization: Start by initializing a variable to track the closest number to zero. Set it initially to the maximum possible integer value.
#include <vector>
#include <cstdlib>
#include <climits>
int findClosestNumber(std::vector<int>& nums) {
int closest = INT_MAX;
for (int num : nums) {
if (std::abs(num) < std::abs(closest) ||
(std::abs(num) == std::abs(closest) && num > closest)) {
closest = num;
}
}
return closest;
}
int closest = INT_MAX;
This ensures we have a starting comparison point that any number in the array will be closer to zero than.
for (int num : nums) {
if (std::abs(num) < std::abs(closest) ||
(std::abs(num) == std::abs(closest) && num > closest)) {
closest = num;
}
}
std::abs(num)
to get the absolute value of the current number.return closest;
This returns the number in the array that is closest to zero based on the criteria defined.
This approach ensures we efficiently find the desired number using a single pass through the array.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?