You are viewing a single comment's thread. Return to all comments →
why is this incorrect :
public static int lilysHomework(List<Integer> arr) { // Write your code here List<Integer> arrCopy = new ArrayList<>(); arrCopy.addAll(arr); Collections.sort(arrCopy); List<Integer> arrCopyRev = new ArrayList<>(); arrCopyRev.addAll(arrCopy); Collections.reverse(arrCopyRev); Map<Integer,Integer> map = new HashMap<>(); Map<Integer,Integer> mapRev = new HashMap<>(); for(int i = 0; i < arr.size();i++){ map.put(arr.get(i),i); mapRev.put(arr.get(i), i); } int swap = 0, swapRev = 0, l = arr.size(); for(int i = 0; i < arrCopy.size();i++){ int current = arrCopy.get(i); int prevLocation = map.get(current); if(prevLocation != i) { map.put(current, i); map.put(arr.get(i), prevLocation); swap++; } int curRev = arrCopyRev.get(i); int prevLocationRev = mapRev.get(curRev); if(prevLocationRev != i) { System.out.println(i+" "+prevLocationRev+" "+ curRev); mapRev.put(curRev, i); mapRev.put(arr.get(i), prevLocationRev); swapRev++; } } return Math.min(swap, swapRev); // 4,5,2,1,3 1,5,2,4,3 1,2,5,4,3 1,2,3,4,5 // 1,2,3,4,5 // 5,4,3,2,1 }
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 →
why is this incorrect :