Given an integer array nums of size n, return _the number with the valueclosest to _0innums. If there are multiple answers, return the number with thelargest value.
Input: nums =[-4,-2,1,4,8]Output: 1Explanation:
The distance from -4 to 0is|-4|=4.The distance from -2 to 0is|-2|=2.The distance from 1 to 0is|1|=1.The distance from 4 to 0is|4|=4.The distance from 8 to 0is|8|=8.Thus, the closest number to 0in the array is1.
classSolution {
public:int findClosestNumber(vector<int>& nums) {
int ans = nums[0];
for (int n : nums) {
if (abs(n) < abs(ans) || (abs(n) == abs(ans) && n > ans)) {
ans = n;
}
}
return ans;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
funcfindClosestNumber(nums []int) int {
ans:=nums[0]
for_, n:=rangenums {
ifabs(n) < abs(ans) || (abs(n) ==abs(ans) &&n > ans) {
ans = n }
}
returnans}
funcabs(xint) int {
ifx < 0 {
return-x }
returnx}
1
2
3
4
5
6
7
8
9
10
11
classSolution {
publicintfindClosestNumber(int[] nums) {
int ans = nums[0];
for (int n : nums) {
if (Math.abs(n) < Math.abs(ans) || (Math.abs(n) == Math.abs(ans) && n > ans)) {
ans = n;
}
}
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
classSolution {
funfindClosestNumber(nums: IntArray): Int {
var ans = nums[0]
for (n in nums) {
if (kotlin.math.abs(n) < kotlin.math.abs(ans) || (kotlin.math.abs(n) == kotlin.math.abs(ans) && n > ans)) {
ans = n
}
}
return ans
}
}
1
2
3
4
5
6
7
classSolution:
deffindClosestNumber(self, nums: list[int]) -> int:
ans = nums[0]
for n in nums:
if abs(n) < abs(ans) or (abs(n) == abs(ans) and n > ans):
ans = n
return ans
1
2
3
4
5
6
7
8
9
10
11
impl Solution {
pubfnfind_closest_number(nums: Vec<i32>) -> i32 {
letmut ans = nums[0];
for&n in&nums {
if n.abs() < ans.abs() || (n.abs() == ans.abs() && n > ans) {
ans = n;
}
}
ans
}
}