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.
This is my old solution in Java language. Unfortunately, it can only pass half of the cases due to exceed the time limitation.
publicstaticintlilysHomework(List<Integer>arr){// Write your code here/* * Idea: - First, it can be proven that an arr with minimal difference between every two elements is a sorted array. - So the sorted array is the destination. - However, there are two results after sorting, increment and decrement array. - The final result is a solution with minimum swap. - A swap is called when an element is not in its final position, or at least, the values are distinct. - If an element is in its final value, it must not need to move. - Moreover, there must be a kind of sort that have the minimum times of swap, if have, it will be the simple approach to solve the problem. + Selection sort seems to be the suitable one. + I try to minimize the number of swaps with this algorithm. * Steps: - Sort in two ways (decre and incre) to compare. 1. Create selection sort that can apply for both requirement. + The sort create temporary list to store the sorting process. 2. In each sort, in each loop, find the first smallest value and check if it need to be swap to the left-most/right-most (depend on the sort) possible position. + If it need, plus 1 for number of swap times, then swap in clone list. 3. Compare the number of swaps between two ways. */intleftSort=sort(arr,true);intrightSort=sort(arr,false);returnMath.min(leftSort,rightSort);}staticintsort(List<Integer>arr,booleanorder){//Init stageintstart,shift,end;if(order){start=0;shift=1;end=arr.size()-1;}else{start=arr.size()-1;shift=-1;end=0;}intswap=0;List<Integer>clone=newArrayList<>();clone.addAll(arr);//Sort stagefor(inti=start;i*shift<=end*shift-1;i+=shift){intminIdx=i;for(intj=i+shift;j*shift<=end*shift;j+=shift){if(clone.get(minIdx)>clone.get(j))minIdx=j;}if(minIdx!=i&&clone.get(minIdx)!=clone.get(i)){swap++;inttemp=clone.get(i);clone.set(i,clone.get(minIdx));clone.set(minIdx,temp);}}returnswap;}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Lily's Homework
You are viewing a single comment's thread. Return to all comments →
This is my old solution in Java language. Unfortunately, it can only pass half of the cases due to exceed the time limitation.