zoukankan      html  css  js  c++  java
  • HR_Minimum Swaps 2

    源代码超时 看了评论区改用了字典序列。

    #!/bin/python3
    
    import math
    import os
    import random
    import re
    import sys
    
    # Complete the minimumSwaps function below.
    def minimumSwaps(arr):
        # n = len(arr)
        # count = 0
        # for i in range(n):
        #     if i > 0:
        #         if i == arr[i-1]:
        #             continue
        #         else:
        #             index = arr.index(i)
        #             temp = arr[i-1]
        #             arr[i-1] = arr[index]
        #             arr [index] = temp
        #             count += 1
        # return count
        ref_arr = sorted(arr)
        index_dict = {v: i for i,v in enumerate(arr)}
        swaps = 0
        
        for i,v in enumerate(arr):
            correct_value = ref_arr[i]
            if v != correct_value:
                to_swap_ix = index_dict[correct_value]
                arr[to_swap_ix],arr[i] = arr[i], arr[to_swap_ix]
                index_dict[v] = to_swap_ix
                index_dict[correct_value] = i
                swaps += 1
                
        return swaps       
    
    if __name__ == '__main__':
        fptr = open(os.environ['OUTPUT_PATH'], 'w')
    
        n = int(input())
    
        arr = list(map(int, input().rstrip().split()))
    
        res = minimumSwaps(arr)
    
        fptr.write(str(res) + '
    ')
    
        fptr.close()
  • 相关阅读:
    提高电脑运行效率
    Android_实验小心得_持续补充中......
    LNMP环境搭建wordpress
    php安装
    mysql、MariaDB(yum)
    Nginx配置(yum)
    httpd配置(yum)
    jumpserver环境搭建
    命令
    vsftpd
  • 原文地址:https://www.cnblogs.com/alfredsun/p/9759162.html
Copyright © 2011-2022 走看看