2239. Find Closest Number to Zero ¶ Time: $O(n)$ Space: $O(1)$ C++JavaPython 1 2 3 4 5 6 7 8class 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 16class Solution { public int findClosestNumber(int[] nums) { int ans = 0; int mn = Integer.MAX_VALUE; for (final int num : nums) if (Math.abs(num) < mn) { mn = Math.abs(num); ans = num; } else if (Math.abs(num) == mn && num > ans) { ans = num; } return ans; } } 1 2 3 4class Solution: def findClosestNumber(self, nums: list[int]) -> int: nums.sort(key=lambda x: (abs(x), -x)) return nums[0]