Find Closest Number to Zero - Complete Solution Guide
Find Closest Number to Zero is LeetCode problem 2239, a Easy level challenge. This complete guide provides step-by-step explanations, multiple solution approaches, and optimized code in python3, java, cpp, c.
Problem Statement
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
Detailed Explanation
The problem asks you to find the integer in an input array `nums` that is closest to zero. If there are multiple numbers with the same minimum distance to zero, the problem specifies that you should return the largest among them. The input is an integer array, and the output is a single integer representing the closest number to zero.
Solution Approach
The provided solution uses a single pass through the input array. It initializes `closest` and `minDiff` with the first element of the array. Then, it iterates through the remaining elements. For each element, it calculates its absolute distance from zero. If this distance is less than the current `minDiff`, it updates `minDiff` and `closest`. If the distance is equal to `minDiff`, it updates `closest` to the larger of the current `closest` and the current element. This ensures that the largest number with the minimum distance is selected. Finally, it returns the `closest` number.
Step-by-Step Algorithm
- Initialize `closest` and `minDiff` with the first element of the array and its absolute value.
- Iterate through the array starting from the second element.
- For each element, calculate its absolute distance from zero.
- If the distance is less than `minDiff`, update `minDiff` and `closest` with the current element.
- If the distance is equal to `minDiff`, update `closest` to the maximum of `closest` and the current element.
- Return the `closest` element.
Key Insights
- Iterating through the array and keeping track of the minimum distance to zero and the corresponding number is the core idea.
- Using absolute value (`abs()`) to calculate the distance from zero is crucial.
- Handling the case where multiple numbers have the same minimum distance requires comparing them and selecting the largest.
Complexity Analysis
Time Complexity: O(n)
Space Complexity: O(1)
Topics
This problem involves: Array.
Companies
Asked at: Tiger Analytics.