Python 阵列中的重要反转
我正在做一个家庭作业,想找出整数数组中的有效倒数。“重大反转”的定义如下: 置换[a0,a1,a2,…,an]中的一个重要反转是,对于某些iPython 阵列中的重要反转,python,arrays,algorithm,divide,Python,Arrays,Algorithm,Divide,我正在做一个家庭作业,想找出整数数组中的有效倒数。“重大反转”的定义如下: 置换[a0,a1,a2,…,an]中的一个重要反转是,对于某些i2aj。例如,a=[4,5,2,1,3]正好有3个重要的反转,因为对于这个置换,a0>2 a3,a1>2 a2,a1>2 a3 解决方案需要具有O(n logn)复杂性。这需要使用分而治之的方法。我选择实现基于合并排序的解决方案 我理解此处给出的拆分操作: def countInversions(list): if(len(list) <= 1
def countInversions(list):
if(len(list) <= 1):
return list, 0
else:
mid = int(len(list)/2)
left, a = countInversions(list[:mid])
right, b = countInversions(list[mid:])
result, c = mergeAndCount(left, right)
return result, (a + b + c)
你就快到了,但有两个问题:
left[i]>2*right[i]
时,您就意味着得出结论,left[i:
中的所有值都大于2*right[i]
,因此您应该将计数增加len(left(i:)
,这与len(left)-i相同。(您只是在上面加1,这就是您的值太低的原因。)def mergeAndCount(left, right):
result = []
count = 0
i,j = 0,0
while(i < len(left) and j < len(right)):
if(left[i] > 2*right[j]):
count += len(left)-i
j += 1
else:
i += 1
i,j = 0,0
while(i < len(left) and j < len(right)):
if(left[i] < right[j]):
result.append(left[i])
i += 1
else:
result.append(right[j])
j += 1
while(left[i:] or right[j:]):
if(left[i:]):
result.append(left[i])
i += 1
if(right[j:]):
result.append(right[j])
j += 1
return result, count
def mergeAndCount(左、右):
结果=[]
计数=0
i、 j=0,0
而(i2*右[j]):
计数+=len(左)-i
j+=1
其他:
i+=1
i、 j=0,0
而(i
def countInversions(list):
if(len(list) <= 1):
return list, 0
else:
mid = int(len(list)/2)
left, a = countInversions(list[:mid])
right, b = countInversions(list[mid:])
result, c = mergeAndCount(left, right)
return result, (a + b + c)
def mergeAndCount(left, right):
result = []
count = 0
i,j = 0,0
while(i < len(left) and j < len(right)):
if(left[i] > 2*right[j]):
count += len(left)-i
j += 1
else:
i += 1
i,j = 0,0
while(i < len(left) and j < len(right)):
if(left[i] < right[j]):
result.append(left[i])
i += 1
else:
result.append(right[j])
j += 1
result.extend(left[i:])
result.extend(right[j:])
return result, count
def mergeAndCount(left, right):
result = []
count = 0
i,j = 0,0
while(i < len(left) and j < len(right)):
if(left[i] > 2*right[j]):
count += len(left)-i
j += 1
else:
i += 1
i,j = 0,0
while(i < len(left) and j < len(right)):
if(left[i] < right[j]):
result.append(left[i])
i += 1
else:
result.append(right[j])
j += 1
while(left[i:] or right[j:]):
if(left[i:]):
result.append(left[i])
i += 1
if(right[j:]):
result.append(right[j])
j += 1
return result, count