You are viewing a single comment's thread. Return to all comments →
Just use dictionary or hasmap to store indexes and update it as you proceed in the 2nd loop.
Dictionary indexDict = new Dictionary(); int countMinSwaps = 0;
for(int index = 0; index < arr.Length; index ++){ indexDict[arr[index]] = index; } for(int index = 0; index < arr.Length; index++){ if(arr[index] == index + 1) continue; else{ int swappingIndex = indexDict[index + 1]; int temp = arr[index]; arr[index] = arr[swappingIndex]; arr[swappingIndex] = temp; indexDict[index + 1] = index; indexDict[arr[swappingIndex]] = swappingIndex; countMinSwaps++; } } return countMinSwaps;
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 →
Here is my c# code with O(2n) time complexity
Just use dictionary or hasmap to store indexes and update it as you proceed in the 2nd loop.
Dictionary indexDict = new Dictionary(); int countMinSwaps = 0;