2239. Find Closest Number to Zero LeetCode Solution
In this guide, you will get 2239. Find Closest Number to Zero LeetCode Solution with the best time and space complexity. The solution to Find Closest Number to Zero problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.
Table of Contents
- Problem Statement
- Complexity Analysis
- Find Closest Number to Zero solution in C++
- Find Closest Number to Zero solution in Java
- Find Closest Number to Zero solution in Python
- Additional Resources
Problem Statement of Find Closest Number to Zero
Given an integer array nums of size n, return the number with the value closest to 0 in nums. If there are multiple answers, return the number with the largest value.
Example 1:
Input: nums = [-4,-2,1,4,8]
Output: 1
Explanation:
The distance from -4 to 0 is |-4| = 4.
The distance from -2 to 0 is |-2| = 2.
The distance from 1 to 0 is |1| = 1.
The distance from 4 to 0 is |4| = 4.
The distance from 8 to 0 is |8| = 8.
Thus, the closest number to 0 in the array is 1.
Example 2:
Input: nums = [2,-1,1]
Output: 1
Explanation: 1 and -1 are both the closest numbers to 0, so 1 being larger is returned.
Constraints:
1 <= n <= 1000
-105 <= nums[i] <= 105
Complexity Analysis
- Time Complexity: O(n)
- Space Complexity: O(1)
2239. Find Closest Number to Zero LeetCode Solution in C++
class Solution {
public:
int findClosestNumber(vector<int>& nums) {
return *ranges::min_element(nums, [](const int a, const int b) {
return abs(a) == abs(b) ? a > b : abs(a) < abs(b);
});
}
};
/* code provided by PROGIEZ */
2239. Find Closest Number to Zero LeetCode Solution in Java
class Solution {
public int findClosestNumber(int[] nums) {
int ans = 0;
int mn = Integer.MAX_VALUE;
for (final int num : nums)
if (Math.abs(num) < mn) {
mn = Math.abs(num);
ans = num;
} else if (Math.abs(num) == mn && num > ans) {
ans = num;
}
return ans;
}
}
// code provided by PROGIEZ
2239. Find Closest Number to Zero LeetCode Solution in Python
class Solution:
def findClosestNumber(self, nums: list[int]) -> int:
nums.sort(key=lambda x: (abs(x), -x))
return nums[0]
# code by PROGIEZ
Additional Resources
- Explore all LeetCode problem solutions at Progiez here
- Explore all problems on LeetCode website here
Happy Coding! Keep following PROGIEZ for more updates and solutions.