Leetcode 2239. Find Closest Number to Zero
Given an integer array nums of size n, find the number that is closest to zero. If there are multiple answers, return the number with the largest value.
Q: What are the constraints on the size of the array n?
A: The size of the array n can be between 1 and 10^3.
Q: Can the array nums contain both positive and negative integers?
A: Yes, the array can contain both positive and negative integers, as well as zero.
Q: What should be the output if the closest numbers to zero are both positive and negative with the same distance from zero? A: Return the positive number.
Q: Do we need to handle any special input cases, such as empty arrays or arrays of a single element?
A: Since the problem guarantees at least one element (size n ≥ 1), we don’t need to worry about empty arrays but should handle single-element arrays.
public class Solution {
public int findClosestNumber(int[] nums) {
// Initialize the closest number to a large positive value
int closest = Integer.MAX_VALUE;
for (int num : nums) {
// If current number is closer to zero or is equally close but positive and larger in value, update closest
if (Math.abs(num) < Math.abs(closest) || (Math.abs(num) == Math.abs(closest) && num > closest)) {
closest = num;
}
}
return closest;
}
public static void main(String[] args) {
Solution sol = new Solution();
int[] nums1 = {-4, -2, 1, 4, 8};
int[] nums2 = {2, -1, 1};
System.out.println(sol.findClosestNumber(nums1)); // Output: 1
System.out.println(sol.findClosestNumber(nums2)); // Output: 1
}
}
n is the number of elements in the array. This is because we iterate through the array once.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?