牛客网 剑指offer 数组中的逆序对 Python3

思路参考了另一篇博客,此处只是将原作者的代码翻译为Python版本:https://blog.csdn.net/lym940928/article/details/91354887 

# -*- coding:utf-8 -*-
class Solution:
    def InversePairs(self, data):
        length=len(data)
        if length<=0:
            return 0
        copy=[]
        for i in range(length):
            copy.append(data[i])
        count=self.InverseHelper(data,copy,0,length-1)
        return count%1000000007
    
    def InverseHelper(self, data, copy, start, end):
        if start==end:
            copy[start]=data[start]
            return 0
        length=(end-start)/2
        left=self.InverseHelper(copy,data,start,start+length)
        right=self.InverseHelper(copy,data,start+length+1,end)
        
        i=start+length
        j=end
        indexcopy=end
        count=0
        while i>=start and j>=start+length+1:
            if data[i]>data[j]:
                copy[indexcopy]=data[i]
                indexcopy-=1
                i-=1
                count=count+j-start-length
            else:
                copy[indexcopy]=data[j]
                indexcopy-=1
                j-=1
        while i>=start:
            copy[indexcopy]=data[i]
            indexcopy-=1
            i-=1
        while j>=start+length+1:
            copy[indexcopy]=data[j]
            indexcopy-=1
            j-=1
        return left+right+count

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值