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. */publicstaticintcountSwaps(List<List<Integer>>indexToValueList){inttotalSwaps=0;Map<Integer,Integer>indexToIndex=newHashMap<>();Set<Integer>startPositions=newHashSet<>();for(inti=0;i<indexToValueList.size();i++){indexToIndex.put(i,indexToValueList.get(i).get(0));}startPositions.addAll(indexToIndex.values());intidx=0;while(!startPositions.isEmpty()){intcurrentSwaps=0;intstartPos=idx;intnextPos=indexToIndex.get(idx);startPositions.remove(startPos);intcurpos=startPos;while(nextPos!=startPos){currentSwaps++;startPositions.remove(nextPos);nextPos=indexToIndex.get(nextPos);curpos=nextPos;}while(!startPositions.contains(idx)){idx++;if(idx>=indexToIndex.size()){break;}}totalSwaps+=currentSwaps;}returntotalSwaps;}publicstaticintlilysHomework(List<Integer>arr){classSortByValueUpimplementsComparator<List<Integer>>{@Overridepublicintcompare(List<Integer>a,List<Integer>b){intva=a.get(1);intvb=b.get(1);if(va>vb){return1;}if(va<vb){return-1;}return0;}}classSortByValueDownimplementsComparator<List<Integer>>{@Overridepublicintcompare(List<Integer>a,List<Integer>b){intva=a.get(1);intvb=b.get(1);if(va<vb){return1;}if(va>vb){return-1;}return0;}}// Write your code here// minimum is sorted. How many swaps to sort?// A sort is a permutation. After sorting, count number// of things not in place. All others must swap, and// swaps can be a cycle, e.g.: a<->b, b<->c, c<->d, d<->a// or a mirror: a<->b. 4 swaps fix 4 in a ring, mirror fixes 2.// Hence we count the loops lengths, e.g. swaps.List<List<Integer>>indexToValueList1=newArrayList<>();List<List<Integer>>indexToValueList2=newArrayList<>();for(inti=0;i<arr.size();i++){List<Integer>entry=newArrayList<>();entry.add(i);entry.add(arr.get(i));indexToValueList1.add(entry);indexToValueList2.add(entry);}Collections.sort(indexToValueList1,newSortByValueUp());Collections.sort(indexToValueList2,newSortByValueDown());ints1=countSwaps(indexToValueList1);ints2=countSwaps(indexToValueList2);if(s1<s2){returns1;}returns2;}}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
An unexpected error occurred. Please try reloading the page. If problem persists, please contact support@hackerrank.com
Lily's Homework
You are viewing a single comment's thread. Return to all comments →
Pedantic.