刷题--数组中的逆序对

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

用类似归并排序的思路。

# -*- coding:utf-8 -*-
class Solution:
    def InversePairsCore(self, data, copy, start, end):
        if start == end:
            copy[start] = data[start]
            return 0

        length = int((end - start) / 2)
        left = self.InversePairsCore(copy, data, start, start + length)
        right = self.InversePairsCore(copy, data, start + length + 1, end)

        i = start + length
        j = end
        copy_index = end
        counter = 0

        while (i >= start) and (j >= start + length + 1):
            if data[i] > data[j]:
                counter += j - start - length
                copy[copy_index] = data[i]
                copy_index -= 1
                i -= 1
            else:
                copy[copy_index] = data[j]
                copy_index -= 1
                j -= 1

        while i >= start:
            copy[copy_index] = data[i]
            copy_index -= 1
            i -= 1

        while j >= start + length + 1:
            copy[copy_index] = data[j]
            copy_index -= 1
            j -= 1

        return (left + right + counter) % 1000000007


    def InversePairs(self, data):
        # write code here
        if data:
            copy = [item for item in data]
            return self.InversePairsCore(data, copy, 0, len(data) - 1)
        else:
            return 0

这道题牛客不知道是不是抽风了,python永远报超时…

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值