We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
functionclosestNumbers(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 */letarr_sorted=arr.sort((a,b)=>a-b)letmin_diff=nullfor(leti=0;i<arr_sorted.length-1;i++){letpair=[arr_sorted[i],arr_sorted[i+1]]letdiff=Math.abs(pair[0]-pair[1])if(!min_diff||diff<min_diff)min_diff=diff}letpairs=[]for(leti=0;i<arr_sorted.length-1;i++){letpair=[arr_sorted[i],arr_sorted[i+1]]letdiff=Math.abs(pair[0]-pair[1])if(diff==min_diff)pairs.push(...pair)}returnpairs;}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Closest Numbers
You are viewing a single comment's thread. Return to all comments →
My answer in Typescript, simple, noted