最小交换次数
题目描述
Description
Given an array of N distinct elementsA[ ], find the minimum number of swaps required to sort the array.Your are required to complete the function which returns an integer denoting the minimum number of swaps, required to sort the array.
Input
The first line of input contains an integer T denoting the no of test cases . Then T test cases follow . Each test case contains an integer N denoting the no of element of the array A[ ]. In the next line are N space separated values of the array A[ ] .(1<=T<=100;1<=N<=100;1<=A[] <=1000)
Output
For each test case in a new line output will be an integer denoting minimum umber of swaps that are required to sort the array.
Sample Input 1
2
4
4 3 2 1
5
1 5 4 3 2
Sample Output 1
2
2
题目解析
将无序数组变为有序数组的最小交换次数
思路解析
这里解释最简单的,也是最好理解的一种方法
-
创建一个数组,该数组是原数组排序后的版本,对应着原数组中元素应该在的正确的位置
-
从头到尾遍历原数组,若原数组与新数组的对应位置上的元素不一致,就在原数组上把应该在这个位置上的元素与当前位置元素对调,使这个位置上放上正确的元素,若一致则向下遍历.
-
这样就保证了每次交换必定使一个元素回到了它自己的位置
eg:9 8 3 7 6 5 1 2 [1, 8, 3, 7, 6, 5, 9, 2] [1, 2, 3, 7, 6, 5, 9, 8] [1, 2, 3, 5, 6, 7, 9, 8] [1, 2, 3, 5, 6, 7, 8, 9]
代码实现
def minSwaps(arr, n):
arr2 = sorted(arr)
count = 0
for i in range(n):
if arr[i] == arr2[i]:
i += 1
continue
else:
k = arr.index(arr2[i]) # O(N)复杂度
arr[i], arr[k] = arr[k], arr[i]
count += 1
print(count)
if __name__ == '__main__':
for _ in range(int(input())):
n = int(input())
arr1 = list(map(int, input().strip().split(" ")))
minSwaps(arr1, n)