问题:https://www.hackerrank.com/challenges/ctci-merge-sort/problem 我的解决方案:
total_swaps = 0
def countInversions(a):
global total_swaps
total_swaps = 0
mergesort(a)
return total_swaps
def merge(arr, left, mid, right):
global total_swaps
buffer = arr[left:mid]
arr_index = left
arr1_index = 0
arr2_index = mid
while arr1_index < len(buffer) and arr2_index < right:
if buffer[arr1_index] > arr[arr2_index]:
arr[arr_index] = arr[arr2_index]
total_swaps += len(buffer) - arr1_index
arr2_index += 1
else:
arr[arr_index] = buffer[arr1_index]
arr1_index += 1
arr_index += 1
while arr1_index < len(buffer):
arr[arr_index] = buffer[arr1_index]
arr_index += 1
arr1_index += 1
def mergesort(arr, left=0, right=None):
if right is None:
right = len(arr)
if right - left <= 1:
return
mid = left + (right-left) // 2
mergesort(arr, left, mid)
mergesort(arr, mid, right)
merge(arr, left, mid, right)
我的11-13测试不及格。如何使我的代码更快?也欢迎任何其他改进。
答案 0 :(得分:1)
这是您可以尝试的一些小改进,但我怀疑它会带来很多好处:
mergesort(a, 0, len(a))
调用countInversions()
,并删除mergesort
中的默认参数值和right is None
上的测试。mergesort()
返回反转计数,该计数将通过添加递归调用的返回值来计算。if right - left <= 5: