class : defcountSmaller(self, nums): result = [] for i in range(len(nums)): temp = 0 for j in range(i,len(nums)): if nums[i] > nums[j]: temp += 1 result.append(temp) return result
# Recursively implementation of Merge Sort and Inversion Pairs counts number = 0 defmerge(left, right): result = [] global number while left and right: if left[0] <= right[0]: result.append(left.pop(0)) #count += len(right) else: result.append(right.pop(0)) number += len(left) if left: result += left if right: result += right return result
defmerge_sort(L): if len(L) <= 1: # When D&C to 1 element, just return it return L mid = len(L) // 2 left = L[:mid] right = L[mid:] left = merge_sort(left) right = merge_sort(right) return merge(left, right) # return the answer of sub-problem if __name__ == "__main__": test = [5,2,6,1,3] print("original:", test) print("Sorted:", merge_sort(test)) print("Inversion Pairs numbers:",number)
class : defcountSmaller(self, nums): if len(nums) == 0: return [] if len(nums) == 1: return [0] #创建一个索引数组用于进行排序 #原数组nums不进行排序,仅仅用作比较大小的作用 index = [i for i in range(len(nums))] #用于存放最终每一个位置上的smaller的个数 result = [0for _ in range(len(nums))] self.merge_sort(self,nums,index,result) return result
defmerge_sort(self,nums,index,result): if len(index) <= 1: return index mid = len(index) // 2 left = index[:mid] right = index[mid:] #递归拆分数组直至全部变为一个元素的list为止 left = self.merge_sort(self,nums,left,result) right = self.merge_sort(self,nums,right,result) #print(left) #print(right) #如果出现了已经构成了有序的数组直接返回 left_pointer = 0 right_pointer = 0 if nums[left[-1]] < nums[right[0]]: return index else: for i in range(len(index)): if left_pointer >= len(left): index[i] = right[right_pointer] #result[index[i]] += len(right) right_pointer += 1 elif right_pointer >= len(right): index[i] = left[left_pointer] left_pointer += 1 result[index[i]] += len(right) elif nums[left[left_pointer]] <= nums[right[right_pointer]]: index[i] = left[left_pointer] left_pointer += 1大专栏 leetcode_315_逆序对问题an> result[index[i]] += len(right[:right_pointer]) else: index[i] = right[right_pointer] #print('process is here') right_pointer += 1 #result[index[i]] += len(left) #print('index_list',index) return index
class : defbisearch(self,tmp,a): left = 0 right = len(tmp) while left < right: mid = (left + right) //2 if tmp[mid] <a: left = mid +1 else: right = mid return left defcountSmaller(self, nums: List[int]) -> List[int]: ans=[] tmp = [] for i in range(len(nums)-1,-1,-1): pos = self.bisearch(tmp, nums[i]) ans.append(pos) tmp.insert(pos,nums[i]) ans.reverse() return ans