数组中的逆序列的错误编程小记
1 class Solution: 2 def InversePairs(self, data): 3 # write code here 4 if not data: 5 return 0 6 tmp = [i for i in data] 7 length = len(data) -1 8 return (self.core(tmp, data, 0, length))%1000000007 9 10 def core(self, tmp, data, low, high): 11 if low >= high: 12 tmp[low] = data[low] 13 return 0 14 mid = (low+high)/2 15 left = self.core(self, data, tmp, low, mid) 16 #在定义函数的时候要加self, 在调用函数,函数前要加, 函数内部则不用加 17 right = self.core(data, tmp, (mid+1), high) 18 i = low 19 j = mid + 1 20 count = 0 21 idx = low 22 while i <= mid and j <= high: 23 if data[i] <= data[j]: 24 i += 1 25 #i 是先自增还是先赋值, 顺序不同会导致list out of index 26 tmp[idx] = data[i] 27 else: 28 j += 1 29 tmp[idx] = data[j] 30 count += (mid - i + 1) 31 idx += 1 32 while i <= mid: 33 tmp[idx] = data[i] 34 i += 1 35 idx += 1 36 while j <= high: 37 tmp[idx] = data[j] 38 j += 1 39 idx +=1 40 return left + right + count
两点教训

浙公网安备 33010602011771号