剑指Offer(Python多种思路实现):数组中的逆序对

剑指Offer(Python多种思路实现):数组中的逆序对

面试51题:

题目:数组中的逆序对

题目描述

在数组中的两个数字,如果前面一个数字大于后面的数字,则这两个数字组成一个逆序对。输入一个数组,求出这个数组中的逆序对的总数P。并将P对1000000007取模的结果输出。 即输出P%1000000007

解题思路一:

    def InversePairs(self, data):
        if len(data) <= 0:
            return 0
        count = 0
        copy = []
        for i in range(len(data)):
            copy.append(data[i])
        copy.sort()
        i = 0
        while len(copy) > i:
            count += data.index(copy[i])
            data.remove(copy[i])
            i += 1
        return count%1000000007

解题思路二:

#暴力法
    def InversePairs2(self, data):
        if len(data)<=1:
            return 0
        count=0
        length=len(data)
        for i in range(length-1):
            for j in range(i+1,length):
                if data[i]>data[j]:
                    count+=1
        return count % 1000000007

解题思路三:

#归并排序法
    def InversePairs3(self, data):
        if len(data)<=0:
            return 0
        length=len(data)
        copy=[0]*length
        for i in range(length):
            copy[i]=data[i]
        #copy数组为原数组data的复制,在后面充当辅助数组
        count=self.Core(data,copy,0,length-1)
        return count % 1000000007
    
    def Core(self,data,copy,start,end):
        if start==end:
            copy[start]=data[start]
            return 0

        length=(end-start)//2 #length为划分后子数组的长度

        left=self.Core(copy,data,start,start+length)
        right=self.Core(copy,data,start+length+1,end)

        #初始化i为前半段最后一个数字的下标
        i=start+length
        #初始化j为后半段最后一个数字的下标
        j=end

        #indexCopy为辅助数组的指针,初始化其指向最后一位
        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 += 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 count+left+right

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值