我真的很喜欢@Ieuan Uys 在 Python 中的解决方案。
我对他的解决方案的改进;
- 当循环少了一次迭代以提高速度时;
while i < len(a) - 1
- Swap 函数被解封装成一个单一的函数。
- 添加了大量代码 cmets 以提高可读性。
我在 python 中的代码。
def minimumSwaps(arr):
#make array values starting from zero to match index values.
a = [x - 1 for x in arr]
#initialize number of swaps and iterator.
swaps = 0
i = 0
while i < len(a)-1:
if a[i] == i:
i += 1
continue
#swap.
tmp = a[i] #create temp variable assign it to a[i]
a[i] = a[tmp] #assign value of a[i] with a[tmp]
a[tmp] = tmp #assign value of a[tmp] with tmp (or initial a[i])
#calculate number of swaps.
swaps += 1
return swaps
详细解释代码对大小为 n 的数组的作用;
我们逐一检查数组中除最后一个(n-1 次迭代)之外的每个值。如果该值与数组索引不匹配,那么我们将该值发送到其索引值等于其值的位置。例如,如果 a[0] = 3。那么这个值应该与 a[3] 交换。 a[0] 和 a[3] 交换。值 3 将位于它应该在的 a[3] 处。一个值被发送到它的位置。我们还有 n-2 次迭代。我对现在的 a[0] 不感兴趣。如果在该位置不为 0,则稍后将其交换为另一个值。因为另一个值也存在于错误的地方,所以后面的while循环会识别出来。
真实例子
a[4, 2, 1, 0, 3]
#iteration 0, check a[0]. 4 should be located at a[4] where the value is 3. Swap them.
a[3, 2, 1, 0, 4] #we sent 4 to the right location now.
#iteration 1, check a[1]. 2 should be located at a[2] where the value is 1. Swap them.
a[3, 1, 2, 0, 4] #we sent 2 to the right location now.
#iteration 2, check a[2]. 2 is already located at a[2]. Don't do anything, continue.
a[3, 1, 2, 0, 4]
#iteration 3, check a[3]. 0 should be located at a[0] where the value is 3. Swap them.
a[0, 1, 2, 3, 4] #we sent 0 to the right location now.
# There is no need to check final value of array. Since all swaps are done.