[算法]最小交换次数

最小交换次数

问题地址

题目描述

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
题目解析

将无序数组变为有序数组的最小交换次数

思路解析

这里解释最简单的,也是最好理解的一种方法

  1. 创建一个数组,该数组是原数组排序后的版本,对应着原数组中元素应该在的正确的位置

  2. 从头到尾遍历原数组,若原数组与新数组的对应位置上的元素不一致,就在原数组上把应该在这个位置上的元素与当前位置元素对调,使这个位置上放上正确的元素,若一致则向下遍历.

  3. 这样就保证了每次交换必定使一个元素回到了它自己的位置

    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)
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值