获得排序数组所需的最小交换

时间:2019-08-11 04:09:04

标签: python

我尝试了以下代码以进行最小限度的交换。有什么问题,因为我只有2/13个测试用例通过了

def minimumSwaps(popularity):
    temp = [0] * (len(popularity) + 1)
    for pos, val in enumerate(popularity):
        temp[val] = pos
        pos += 1
    swaps = 0
    for i in range(len(popularity)):
        if popularity[i] != i+1:
            swaps += 1
            t = popularity[i]
            popularity[i] = i+1
            popularity[temp[i+1]] = t
            temp[t] = temp[i+1]
    return swaps

0 个答案:

没有答案