1. 程式人生 > >劍指Offer33:陣列中的逆序對

劍指Offer33:陣列中的逆序對

思路:

利用歸併排序統計逆序對的個數。即將陣列不斷平均分,當分到只剩2個元素和或者小於時,根據具體元素的大小判斷是否存在逆序對,若存在則調換,以免重複統計。總計結束後返回上一層繼續判斷

# -*- coding:utf-8 -*-
class Solution:
    def InversePairs(self, data):
        return self.inverseCount(data[:], 0, len(data)-1, data[:]) % 1000000007
       
    def inverseCount(self, tmp, start, end, data):
        if end - start < 1:
            return 0
        if end - start == 1:
            if data[start] <= data[end]:
                return 0
            else:
                tmp[start], tmp[end] = data[end], data[start]
                return 1
        mid = (start+end) // 2
        cnt = self.inverseCount(data, start, mid, tmp) + self.inverseCount(data, mid+1, end, tmp)
        i = start
        j = mid + 1
        ind = start
           
        while(i <= mid and j <= end):
            if data[i] <= data[j]:
                tmp[ind] = data[i]
                i += 1
            else:
                tmp[ind] = data[j]
                cnt += mid - i + 1
                j += 1
            ind += 1
        while(i <= mid):
            tmp[ind] = data[i]
            i += 1
            ind += 1
        while(j <= end):
            tmp[ind] = data[j]
            j += 1
            ind += 1
        return cnt

大佬的思想,小菜鳥是不是要轉行呀,不適合不適合