Closest Numbers

Sort by

recency

|

627 Discussions

|

  • + 0 comments

    vector closestNumbers(vector arr) { int n=arr.size(); vectora; sort(arr.begin(),arr.end()); int k; for(int i=0;id; for(int i=0;i

  • + 0 comments
    function closestNumbers(arr) {
      const sortedArray = [...arr].sort((a, b) => a - b);
      const startingPoint = sortedArray.splice(0, 2);
    
      return sortedArray.reduce((acc, element, index) => {
        const previosElement = index === 0 ? acc[1] : sortedArray[index - 1];
        const currentDifference = Math.abs(element - previosElement);
        const existingDifference = Math.abs(acc[0] - acc[1]);
    
        if (currentDifference < existingDifference) return [previosElement, element];
        if (currentDifference === existingDifference) return acc.concat(previosElement, element);
    
        return acc;
      }, startingPoint);
    }
    
  • + 0 comments
    def closestNumbers(arr):
        # Write your code here
        arr.sort()
        min_abs = abs(arr[0] - arr[1])
        min_arr = [arr[0], arr[1]]
        for i in range(1, len(arr)-1):
            if abs(arr[i] - arr[i+1]) > min_abs:
                continue
            elif abs(arr[i] - arr[i+1]) == min_abs:
                min_arr.append(arr[i])
                min_arr.append(arr[i+1])
            elif abs(arr[i] - arr[i+1]) < min_abs:
                min_abs = abs(arr[i] - arr[i+1])
                min_arr = [arr[i], arr[i+1]]
        return min_arr
    
  • + 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;
    }
    
  • + 0 comments
    D = {}
        arr = sorted(arr)
        mini = 10e6
        for i in range(len(arr) -1):
            diff = arr[i+1] - arr[i]
            if diff < mini: 
                mini = diff
                D[diff] = [arr[i+1], arr[i]]
            elif diff == mini:
                D[diff].extend([arr[i+1], arr[i]])
        
        result = sorted(D[mini])       
        return result