Skip to content

2239. Find Closest Number to Zero 👍

  • Time: $O(n)$
  • Space: $O(1)$
1
2
3
4
5
6
7
8
class Solution {
 public:
  int findClosestNumber(vector<int>& nums) {
    return *ranges::min_element(nums, [](const int a, const int b) {
      return abs(a) == abs(b) ? a > b : abs(a) < abs(b);
    });
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution {
  public int findClosestNumber(int[] nums) {
    int ans = 0;
    int min = Integer.MAX_VALUE;

    for (final int num : nums)
      if (Math.abs(num) < min) {
        min = Math.abs(num);
        ans = num;
      } else if (Math.abs(num) == min && num > ans) {
        ans = num;
      }

    return ans;
  }
}
1
2
3
4
class Solution:
  def findClosestNumber(self, nums: List[int]) -> int:
    nums.sort(key=lambda x: (abs(x), -x))
    return nums[0]