Physical Address
304 North Cardinal St.
Dorchester Center, MA 02124
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] <= 105
int findClosestNumber(vector<int>& nums) {
return *min_element(begin(nums), end(nums), [](int a, int b) {
return abs(a) < abs(b) || (abs(a) == abs(b) && a > b);
});
}
def findClosestNumber(self, A):
return max([-abs(a), a] for a in A)[1]
// If absolute of n is less than min, update the closest_num
// If absolute of n is same of as min, update the bigger closest_num
class Solution {
public int findClosestNumber(int[] nums) {
int min = Integer.MAX_VALUE, closest_num = 0;
for(int n : nums) {
if(min > Math.abs(n)) {
min = Math.abs(n);
closest_num = n;
} else if(min == Math.abs(n) && closest_num < n) {
closest_num = n;
}
}
return closest_num;
}
}
var findClosestNumber = function(nums) {
let closest = Infinity;
for (let num of nums) {
if (Math.abs(num) < Math.abs(closest)) {
closest = num
} else if (Math.abs(num) === Math.abs(closest)) {
closest = Math.max(num, closest)
}
}
return closest;
};
import kotlin.math.abs
class Solution {
fun findClosestNumber(nums: IntArray): Int {
var closest: Int? = null
for (num in nums) {
if (closest == null) {
closest = num
} else {
if (abs(num) < abs(closest)) {
closest = num
} else if (abs(num) == abs(closest)) {
if (num > closest) {
closest = num
}
}
}
}
return closest!!
}
}
In our experience, we suggest you solve this Find Closest Number to Zero LeetCode Solution and gain some new skills from Professionals completely free and we assure you will be worth it.
If you are stuck anywhere between any coding problem, just visit Queslers to get the Find Closest Number to Zero LeetCode Solution
I hope this Find Closest Number to Zero LeetCode Solution would be useful for you to learn something new from this problem. If it helped you then don’t forget to bookmark our site for more Coding Solutions.
This Problem is intended for audiences of all experiences who are interested in learning about Data Science in a business context; there are no prerequisites.
Keep Learning!
More Coding Solutions >>