1 def minSwapsCouples(row): 2 position=dict((row[i],i) for i in range(len(row))) 3 #建立一个由 4 swap_cnt=0 5 i=0 6 while(i<len(row)): 7 if row[i]%2==0: 8 if row[i+1]==row[i]+1: 9 i+=2 10 else: 11 index=position[row[i]+1] 12 # 更新position 13 position[row[index]]=i+1 14 position[row[i+1]]=index 15 row[index],row[i+1]= row[i+1] ,row[index] 16 17 18 swap_cnt+=1 19 i+=2 20 else: 21 22 if row[i+1]==row[i]-1: 23 i+=2 24 else: 25 index = position[row[i]-1] 26 # 更新position 27 position[row[index]] = i + 1 28 position[row[i + 1]] = index 29 row[index], row[i + 1] = row[i + 1], row[index] 30 31 swap_cnt += 1 32 i += 2 33 34 print(row) 35 36 return swap_cnt