OJ最小交换次数

文章目录

最小交换次数

最小交换次数
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);

        }
    }
}

对于每一个位置如果现在的元素和目标元素不相等,则将现有元素换到它应该处于的位置,直到相等。
再进行下个位置。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值