Closest Numbers

  • + 0 comments

    My rust solution:

    fn closestNumbers(arr: &[i32]) -> Vec<i32> {
        let mut arr = Vec::from(arr);
        arr.sort();
    
        let mut pairs: Vec<(i32, i32)> = arr
            .windows(2)
            .map(|window| (window[0], window[1]))
            .collect();
    
        pairs.sort_by(|a, b| (a.1 - a.0).cmp(&(b.1 - b.0)));
    
        let closest_pair = pairs[0];
    
        pairs
            .iter()
            .take_while(|pair| pair.1 - pair.0 == closest_pair.1 - closest_pair.0)
            .flat_map(|pair| [pair.0, pair.1])
            .collect()
    }