我解决了 HackerRank 上的最小交换 2 数组挑战 ( https://www.hackerrank.com/challenges/minimum-swaps-2/problem )。我的解决方案对于较大的数组会超时,因此我回去重构代码。我想到了我的新解决方案,几乎在我提交后我就意识到它行不通。然而,它确实......完美,但我要疯狂地试图找出原因。至少,为什么它没有陷入无限的 while 循环中,反复来回交换两个数组值?除了显而易见的事情之外,假设它确实神奇地跳出了循环,如果我们正在寻找,在用于计算交换的条件下它怎么可能得到正确的答案>最少 交换次数?我在代码中的不同位置添加了打印语句,以尝试查看发生了什么并自己理解它,但它们只会增加困惑。有人能带我了解一下我荒谬的天才的逻辑吗?或者这是一个侥幸?
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the minimumSwaps function below.
def minimumSwaps(arr):
swaps = 0
for x in range(0, n - 1):
while arr[x] != x + 1:
arr[arr[x] - 1], arr[x] = arr[x], arr[arr[x] - 1]
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) + '\n')
fptr.close()
最佳答案
如果您想按照您的步骤操作
list swap_index_1 swap_index_2
0 [7, 9, 6, 4, 2, 5, 1, 3, 8, 0] NaN NaN
1 [1, 9, 6, 4, 2, 5, 7, 3, 8, 0] 0.0 0.0
2 [1, 8, 6, 4, 2, 5, 7, 3, 9, 0] 1.0 7.0
3 [1, 3, 6, 4, 2, 5, 7, 8, 9, 0] 1.0 2.0
4 [1, 6, 3, 4, 2, 5, 7, 8, 9, 0] 1.0 5.0
5 [1, 5, 3, 4, 2, 6, 7, 8, 9, 0] 1.0 4.0
6 [1, 2, 3, 4, 5, 6, 7, 8, 9, 0] 1.0 1.0
<小时/>
from random import shuffle
import pandas as pd
steps = []
def log(arr, s1, s2):
steps.append(dict(list=arr.copy(), swap_index_1=s1, swap_index_2=s2))
n = 10
arr = list(range(n))
shuffle(arr)
swaps = 0
log(arr, None, None)
for x in range(0, n - 1):
while arr[x] != x + 1:
arr[arr[x] - 1], arr[x] = arr[x], arr[arr[x] - 1]
swaps += 1
log(arr, x, arr[x] - 1)
steps = pd.DataFrame(steps)
print(steps)
关于python - 为什么这个解决方案没有陷入无限循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56568987/