Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- https://practice.geeksforgeeks.org/problems/minimum-swaps/1#
- class Solution:
- #Function to find the minimum number of swaps required to sort the array.
- def minSwaps(self, nums):
- n=len(nums)
- seen=set()
- ans=0
- adict=sorted(((j,i) for i,j in enumerate(nums)),key=lambda x:x[0])
- for key,val in adict:
- if key in seen:
- continue
- seen.add(key)
- swaps=0
- idx=val
- while adict[idx][0] not in seen:
- seen.add(adict[idx][0])
- swaps+=1
- idx=adict[idx][1]
- ans+=swaps
- return ans
- #{
- # Driver Code Starts
- if __name__ == '__main__':
- T=int(input())
- for i in range(T):
- n = int(input())
- nums = list(map(int, input().split()))
- obj = Solution()
- ans = obj.minSwaps(nums)
- print(ans)
- # } Driver Code Ends
Advertisement
Add Comment
Please, Sign In to add comment