LeetCode 2239: Find Closest Number to Zero Solution
Master LeetCode problem 2239 (Find Closest Number to Zero), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
2239. Find Closest Number to Zero
Problem Explanation
Explanation
To find the number closest to zero in the given array, we iterate through the array and keep track of the number with the smallest absolute value. If there are multiple numbers with the same absolute value, we return the number with the largest value. We can achieve this by comparing the absolute values and updating the closest number and keeping track of the largest number seen so far.
- Start by initializing variables
closestNumberandlargestNumberto the first element of the array. - Iterate through the array, updating
closestNumberandlargestNumberbased on the absolute values and values of the current element. - Return the
closestNumberas the result.
The time complexity of this solution is O(n) where n is the number of elements in the array. The space complexity is O(1).
Solution Code
public int findClosestToZero(int[] nums) {
int closestNumber = nums[0];
int largestNumber = nums[0];
for (int i = 1; i < nums.length; i++) {
if (Math.abs(nums[i]) < Math.abs(closestNumber) || (Math.abs(nums[i]) == Math.abs(closestNumber) && nums[i] > closestNumber)) {
closestNumber = nums[i];
largestNumber = Math.max(largestNumber, nums[i]);
}
}
return closestNumber;
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 2239 (Find Closest Number to Zero)?
This page provides optimized solutions for LeetCode problem 2239 (Find Closest Number to Zero) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 2239 (Find Closest Number to Zero)?
The time complexity for LeetCode 2239 (Find Closest Number to Zero) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 2239 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2239 in Java, C++, or Python.