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.
Java 8 - used stream to create a set if index that are sorted.
publicstaticintlilysHomework(List<Integer>arr){// The key to solving this problem is to create a sorted indexs// and count the number of the swaps it takes to get things// in the corrector order.List<Integer>indicesAssending=IntStream.range(0,arr.size()).boxed().sorted(Comparator.comparingInt(i->arr.get(i))).collect(Collectors.toList());List<Integer>indicesDesending=indicesAssending.stream().collect(Collectors.toList());Collections.reverse(indicesDesending);intresultAssending=swapToOrder(indicesAssending);intresultDesending=swapToOrder(indicesDesending);returnMath.min(resultAssending,resultDesending);}/** Swap each sorted indice into it proper location **/privatestaticintswapToOrder(List<Integer>indices){intresult=0;for(inti=0;i<indices.size();){if(i!=indices.get(i).intValue()){++result;swap(indices,i,indices.get(i));}else{++i;}}returnresult;}/** Simple swaping of two indices values**/privatestaticvoidswap(List<Integer>arr,inti1,inti2){Integerv1=arr.get(i1);arr.set(i1,arr.get(i2));arr.set(i2,v1);}
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 →
Java 8 - used stream to create a set if index that are sorted.