EasyNo. 2239
Find Closest Number to Zero — LeetCode 2239 Python Solution
- Topics
- Array
- Reading time
- 2 min
- Source
- leetcode.com
The problem
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
- Input
- nums = [-4,-2,1,4,8]
- Output
- 1
- Explanation
- The distance from -4 to 0 is |-4| = 4.
Python solution
class Solution:
def findClosestNumber(self, nums: List[int]) -> int:
ans, d = 0, inf
for x in nums:
if (y := abs(x)) < d or (y == d and x > ans):
ans, d = x, y
return ansComplexity
- Time
- O(n)where n is the length of the array
- Space · auxiliary
- O(1)
Related problems
| No. | Problem | Difficulty |
|---|---|---|
| 0057 | Insert Interval | Medium |
| 0228 | Summary Ranges | Easy |
| 0485 | Max Consecutive Ones | Easy |
| 0665 | Non-decreasing Array | Medium |
| 0674 | Longest Continuous Increasing Subsequence | Easy |
| 0699 | Falling Squares | Hard |
Frequently asked questions
- How hard is LeetCode 2239. Find Closest Number to Zero?
LeetCode 2239. Find Closest Number to Zero is rated Easy on LeetCode.
- What is the time complexity of LeetCode 2239. Find Closest Number to Zero?
The Python solution on this page runs in O(n), where n is the length of the array.
- What is the space complexity of LeetCode 2239. Find Closest Number to Zero?
The Python solution on this page uses O(1) auxiliary space.
- What topics does LeetCode 2239. Find Closest Number to Zero cover?
LeetCode 2239. Find Closest Number to Zero is tagged Array on LeetCode.