Description Solution: BFS & Cycle Counting BFS level-by-level and get minimum swaps for the node values at each level. How to calculate the minimum swaps to sort an array: Get the index of each number in its sorted position (store in a hashmap indexes ) For each nums[i] , store the number we need to swap with to place nums[i] in its sorted position (store in a hashmap next ) Find the size of each cycle. Get the total sum of each ( cycle size - 1 ). Why sum of ( cycle size - 1 ) is correct: If cycle size = 1 , we don't need any swaps. If cycle size = 2 , we only need 1 swap. If cycle size = 3 , we need 2 swaps. --- Main Proof --- Starting from the smallest number in the cycle, swap each nums[i] (where nums[i] is in the cycle) into its sorted position. Since the number is now in the correct position, it is no longer in the cycle and this leaves us with a cycle of size ( n - 1 ), where n = ...
Comments
Post a Comment