You are viewing a single comment's thread. Return to all comments →
A bit cleaner version of Java code that passes all test cases. Swaps in place for sake of simplicity
static int minimumSwaps(int[] arr) { int swaps = 0; for(int current=0; current<arr.length; ) { if(!inPlace(arr, current)) { ++swaps; swapInPlace(arr, current); } else { ++current; } } return swaps; } private static void swapInPlace(int[] arr, int index) { int newIndex = arr[index] - 1; int tmp = arr[newIndex]; arr[newIndex] = arr[index]; arr[index] = tmp; } private static boolean inPlace(int[] arr, int index) { return arr[index] == index + 1; }
Seems like cookies are disabled on this browser, please enable them to open this website
Minimum Swaps 2
You are viewing a single comment's thread. Return to all comments →
A bit cleaner version of Java code that passes all test cases. Swaps in place for sake of simplicity