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] <= 105This approach involves iteratively traversing the array or list to find the solution. It's important to use a loop to iterate through the elements, maintaining variables to track the current state, and update them as needed. This approach is typical for problems such as finding maximums, minimums, or accumulating values.
This C program calculates the sum of an array using an iterative approach. It loops through each array element, accumulating the total.
C++
Java
Python
C#
JavaScript
Time Complexity: O(n)
Space Complexity: O(1)
This approach uses recursion to solve the problem by breaking it down into sub-problems. Recursive solutions can be elegant and succinct but may not always be optimal for large input sizes due to stack overflow risks and lack of tail-call optimization in many languages.
This solution uses recursion to sum an array in C. The base case checks if there are no elements left, and the recursive case adds the last element to the rest.
C++
Java
Python
C#
JavaScript
Time Complexity: O(n)
Space Complexity: O(n) (due to call stack)
| Approach | Complexity |
|---|---|
| Approach 1: Iterative Solution with Array Traversal | Time Complexity: O(n) |
| Approach 2: Recursive Solution | Time Complexity: O(n) |
Find K Closest Elements - Leetcode 658 - Python • NeetCode • 86,973 views views
Watch 9 more video solutions →Practice Find Closest Number to Zero with our built-in code editor and test cases.
Practice on FleetCode