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.
publicstaticList<Integer>closestNumbers(List<Integer>arr){if(arr.size()==2)returnArrays.asList(arr.get(0),arr.get(1));//goal: find pair with smallest abs diff//sort arrCollections.sort(arr);//init new minintmin=arr.get(1)-arr.get(0);List<Integer>minIdices=newArrayList<>();minIdices.add(arr.get(0));minIdices.add(arr.get(1));//compare adj elementsfor(inti=2;i<arr.size();i++){intdiff=arr.get(i)-arr.get(i-1);//if new min is found clear ans listif(diff<min){min=diff;minIdices.clear();minIdices.add(arr.get(i-1));minIdices.add(arr.get(i));}elseif(diff==min){minIdices.add(arr.get(i-1));minIdices.add(arr.get(i));}}returnminIdices;}
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 Java solution: