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.
Could you please explain the logic? How do you arrive to use Math.min() part? This is really fast. The one I have written is failing for Testcase 13.
static int minimumSwaps1(int[] arr) {
int currentMin = 1;
int currentInd = 0;
int minSwapsCount = 0;
while (currentMin != arr.length) {
for (int i = currentInd; i<arr.length; i++) {
if (arr[i] == currentMin) {
if (i == currentInd) {
//It is already sorted..
currentInd++;
currentMin++;
break;
}
swap(arr, i, currentInd);
minSwapsCount++;
currentInd++;
currentMin++;
}
}
}
return minSwapsCount;
}
Cookie support is required to access HackerRank
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 →
Could you please explain the logic? How do you arrive to use Math.min() part? This is really fast. The one I have written is failing for Testcase 13.
static int minimumSwaps1(int[] arr) { int currentMin = 1; int currentInd = 0; int minSwapsCount = 0; while (currentMin != arr.length) { for (int i = currentInd; i<arr.length; i++) { if (arr[i] == currentMin) { if (i == currentInd) { //It is already sorted.. currentInd++; currentMin++; break; } swap(arr, i, currentInd); minSwapsCount++; currentInd++; currentMin++; } } } return minSwapsCount; }