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.
classResult{/* * Complete the 'lilysHomework' function below. * * The function is expected to return an INTEGER. * The function accepts INTEGER_ARRAY arr as parameter. */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. - Using minimum number of swaps theory to calculate the number of swaps - Numbers that need to be swapped form circles in which the length of the circle minus 1 is the number of swaps. * Steps: - Calculate the minimum number of swaps in case increment list and decrement list. 1. Create an object named "pair" that contains the value of the element and its primary index position. 2. Get all the pair in a list, sort that list with customized comparator. 3. Traverse through the pair list, using the graph theory to identify circles consisting the group of element need to be swapped. 4. Specify the number of swaps. 5. Get the total number in each order of the list. - Find the minimum number of swaps between two ways. */List<Pair>arrPos=newArrayList<>();for(inti=0;i<arr.size();i++){arrPos.add(newPair(arr.get(i),i));}arrPos.sort(newComparator<Pair>(){publicintcompare(Pairp1,Pairp2){if(p1.value<p2.value){return-1;}elseif(p1.value==p2.value)return0;elsereturn1;}});intres=0,revRes=0;boolean[]vis=newboolean[arrPos.size()];boolean[]revVis=newboolean[arrPos.size()];//Compare origin list with increment sorted listfor(inti=0;i<arrPos.size();i++){if(vis[i]||arrPos.get(i).index==i)continue;intcircleLength=0;intj=i;while(!vis[j]){vis[j]=true;circleLength++;j=arrPos.get(j).index;}if(circleLength>0)res+=circleLength-1;}//Compare origin list with decrement sorted listCollections.reverse(arrPos);for(inti=0;i<arrPos.size();i++){if(revVis[i]||arrPos.get(i).index==i)continue;intcircleLength=0;intj=i;while(!revVis[j]){revVis[j]=true;circleLength++;j=arrPos.get(j).index;}if(circleLength>0)revRes+=circleLength-1;}returnMath.min(res,revRes);}}classPair{intvalue;intindex;Pair(intv,inti){value=v;index=i;}}
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 new solution in Java language.