Closest Numbers

  • + 0 comments

    Rust best solution

    If you’re looking for solutions to the 3-month preparation kit in either Python or Rust, you can find them below: my solutions

    fn closest_numbers(arr: &[i32]) -> Vec<i32> {
        //Time complexity: O(n*log(n))
        //Space complexity (ignoring input): O(n)
        let mut arr = arr.to_vec();
        arr.sort_unstable();
    
        let mut minimun_value = arr[1] - arr[0];
        let mut pairs = vec![arr[0], arr[1]];
        for index in 2..arr.len() {
            if (arr[index] - arr[index - 1]) == minimun_value {
                pairs.push(arr[index - 1]);
                pairs.push(arr[index]);
            }
            if (arr[index] - arr[index - 1]) < minimun_value {
                minimun_value = arr[index] - arr[index - 1];
                pairs = vec![arr[index - 1], arr[index]];
            }
        }
        pairs
    }