Closest Numbers

  • + 0 comments

    My answer in Typescript, simple, noted

    function closestNumbers(arr: number[]): number[] {
        /**
         * simple
         * 
         * 1. find [arr_sorted], sorted array of the [arr]
         * 2. find [min_diff], smallest difference between 2 adj element in [arr_sorted]
         * 3. loop [arr_sorted], only take pair that have difference smallest
         * 4. return
         */
        let arr_sorted = arr.sort((a, b) => a - b)
    
        let min_diff = null
        for (let i = 0; i < arr_sorted.length - 1; i++) {
            let pair = [arr_sorted[i], arr_sorted[i + 1]]
            let diff = Math.abs(pair[0] - pair[1])
    
            if (!min_diff || diff < min_diff) min_diff = diff
        }
    
        let pairs = []
        for (let i = 0; i < arr_sorted.length - 1; i++) {
            let pair = [arr_sorted[i], arr_sorted[i + 1]]
            let diff = Math.abs(pair[0] - pair[1])
    
            if (diff == min_diff) pairs.push(...pair)
        }
    
        return pairs;
    }