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.
nums
?nums
?Let’s write the code, keeping in mind to handle edge cases as well.
def findClosestNumber(nums):
# Handle the case where nums is empty
if not nums:
return None # Assuming returning None for an empty list
# Initialize the closest number to a very large value
closest_num = float('inf')
for num in nums:
# Check if this number is closer to zero than the closest_num found so far
if abs(num) < abs(closest_num):
closest_num = num
# If it ties for closeness, choose the larger value
elif abs(num) == abs(closest_num):
closest_num = max(closest_num, num)
return closest_num
closest_num
set to positive infinity.nums
, check the following:
closest_num
, update closest_num
.closest_num
to be the maximum of the current number and closest_num
.closest_num
.nums
. This is because we only iterate through the list 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?