2239. Find Closest Number to Zero Easy

@problem@discussion
#Array



1/**
2 * [2239] Find Closest Number to Zero
3 *
4 * 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.
5 *  
6 * Example 1:
7 * 
8 * Input: nums = [-4,-2,1,4,8]
9 * Output: 1
10 * Explanation:
11 * The distance from -4 to 0 is |-4| = 4.
12 * The distance from -2 to 0 is |-2| = 2.
13 * The distance from 1 to 0 is |1| = 1.
14 * The distance from 4 to 0 is |4| = 4.
15 * The distance from 8 to 0 is |8| = 8.
16 * Thus, the closest number to 0 in the array is 1.
17 * 
18 * Example 2:
19 * 
20 * Input: nums = [2,-1,1]
21 * Output: 1
22 * Explanation: 1 and -1 are both the closest numbers to 0, so 1 being larger is returned.
23 * 
24 *  
25 * Constraints:
26 * 
27 * 1 <= n <= 1000
28 * -10^5 <= nums[i] <= 10^5
29 * 
30 */
31pub struct Solution {}
32
33// problem: https://leetcode.com/problems/find-closest-number-to-zero/
34// discuss: https://leetcode.com/problems/find-closest-number-to-zero/discuss/?currentPage=1&orderBy=most_votes&query=
35
36// submission codes start here
37
38impl Solution {
39    pub fn find_closest_number(nums: Vec<i32>) -> i32 {
40        let mut min = i32::MAX;
41        let mut result = 0;
42        for n in nums {
43            let new_diff = n.abs();
44            if new_diff == min && n > result {
45                result = n;
46            } else if new_diff < min {
47                min = new_diff;
48                result = n;
49            }
50        }
51        result
52    }
53}
54
55// submission codes end
56
57#[cfg(test)]
58mod tests {
59    use super::*;
60
61    #[test]
62    fn test_2239() {
63        assert_eq!(Solution::find_closest_number(vec![-4,-2,1,4,8]), 1);
64    }
65}
66


Back
© 2025 bowen.ge All Rights Reserved.