PAT(Advanced Level) Practice(with python)——1067 Sort with Swap(0, i)

PAT(Advanced Level) Practice(with python)——1067 Sort with Swap(0, i)_第1张图片

Code

# 输入有毒,需避坑
# N = int(input())
L = list(map(int,input().split()))
N = L[0] 
L = L[1:]
res = 0
for i in range(1,N):
    while L[0]!=0:
        # 把所有不在正常位置下的数换到正常
        t = L[0]
        L[0],L[t] = L[t],L[0]
        res+=1
    if L[i]!=i:
        # 换完全后如果对应位置下的数不是目标数,那就和0交换
        L[0],L[i] = L[i],L[0]
        res+=1
        
print(res)

PAT(Advanced Level) Practice(with python)——1067 Sort with Swap(0, i)_第2张图片

你可能感兴趣的:(PAT,python,算法)