文章目录
最小交换次数
最小交换次数
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
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int T = scan.nextInt();//测试数
while(T-->0){
int length = scan.nextInt();
Integer[] array = new Integer[length];//原数组
for(int i=0;i<length;i++){
array[i] = scan.nextInt();
}
Integer[] target = array.clone();//目标数组
Arrays.sort(target,new Comparator<Integer>(){
@Override
public int compare(Integer o1,Integer o2){
if(o1>o2){
return 1;
}
if(o1<o2){
return -1;
}
return 0;
}
});
HashMap<Integer,Integer> map = new HashMap<>();
for(int i=0;i<length;i++){
map.put(target[i],i); //<目标数组元素,其在目标数组的位置>
}
int result = 0;
for(int i=0;i<length;i ++){
while(map.get(array[i])!=i){
int temp = array[i];
array[i] = array[map.get(array[i])];
array[map.get(temp)] = temp;
result++;
}
}
System.out.println(result);
}
}
}
对于每一个位置如果现在的元素和目标元素不相等,则将现有元素换到它应该处于的位置,直到相等。
再进行下个位置。