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.
I have looked up some codes in here and found 2 common solutions: using loop-nest or sort and check adjacent elements.
I came up with using Insertion sort as an idea to both sort and check minimum abs difference. The idea is to control the break point and reduce the amount of comparision (comparing to loop-nest). However, it result in running out of time for the last case. Can someone explain?
publicstaticintminimumAbsoluteDifference(List<Integer>arr){// Write your code hereintminAbsDif=(int)Math.abs(arr.get(0)-arr.get(1));intcurVal;intdif;for(inti=1;i<arr.size();i++){curVal=arr.get(i);intk=i-1;while(k>=0){dif=arr.get(k)-curVal;if((int)Math.abs(dif)<minAbsDif)minAbsDif=(int)Math.abs(dif);if(minAbsDif==0)return0;if(dif>0){arr.set(k+1,arr.get(k));k--;}else{break;}}arr.set(k+1,curVal);}returnminAbsDif;}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Minimum Absolute Difference in an Array
You are viewing a single comment's thread. Return to all comments →
I have looked up some codes in here and found 2 common solutions: using loop-nest or sort and check adjacent elements. I came up with using Insertion sort as an idea to both sort and check minimum abs difference. The idea is to control the break point and reduce the amount of comparision (comparing to loop-nest). However, it result in running out of time for the last case. Can someone explain?