You are viewing a single comment's thread. Return to all comments →
Come up with the similar solution, but moved both right and left pointers if numbers are already in place.
static int minimumSwaps(int[] arr) { int first = 0, last = arr.length - 1; int swaps = 0; while (first < last) { while (arr[first] == first + 1 && first < last) first++; if (first < last) { int temp = arr[arr[first] - 1]; arr[arr[first] - 1] = arr[first]; arr[first] = temp; swaps++; } } return swaps; }
Edited to remove the while loop for the last index as it doesn't make much sense here nor improving number of iterations
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 →
Come up with the similar solution, but moved both right and left pointers if numbers are already in place.
Edited to remove the while loop for the last index as it doesn't make much sense here nor improving number of iterations