zoukankan      html  css  js  c++  java
  • 数组中的逆序对(python)

    题目描述

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

    输入描述:

    题目保证输入的数组中没有的相同的数字

    数据范围:

    对于%50的数据,size<=10^4

    对于%75的数据,size<=10^5

    对于%100的数据,size<=2*10^5

    示例1

    输入

    复制
    1,2,3,4,5,6,7,0

    输出

    复制
    7
    # -*- coding:utf-8 -*-
    class Solution:
        def InversePairs(self, data):
            # write code here
            #用归并排序,归并拼接后用计算排序时元素的index变动了少
            _,s=self.MergeSort(data)
            return s%1000000007
        def MergeSort(self,data):
            n=len(data)
            #递归基
            if n==1:return data, 0
            #分两半来排序
            part1,part2=data[:n//2],data[n//2:]
            sorted_part1,s1=self.MergeSort(part1)
            sorted_part2,s2=self.MergeSort(part2)
            #排序后拼接这两半,拼接后先计数,然后将两个有序序列合并
            s,sorted_temp=0,sorted_part1+sorted_part2
            #用p、q两个指针指向两段,计算q中每个元素离插入点的index差
            p,q,len1,len_all=0,sorted_temp.index(sorted_part2[0]),len(sorted_part1),len(sorted_temp)
            while p<len1 and q<len_all:
                #移动p使p成为插入排序的插入点,计算要移动多少个位置
                while p<len1:
                    if sorted_temp[q]<sorted_temp[p]:
                        s+=len1-p
                        break
                    p+=1
                q+=1
            #完成排序,并把排序后的内容回溯给上一级做准备
            l=[]
            p,q=0,sorted_temp.index(sorted_part2[0])
            while p<len1 and q<len_all:
                if sorted_temp[p]<sorted_temp[q]:
                    l.append(sorted_temp[p])
                    p+=1
                else:
                    l.append(sorted_temp[q])
                    q+=1
            if p==len1:l+=sorted_temp[q:]
            if q==len_all:l+=sorted_part1[p:]
            return l,s+s1+s2
    

      

  • 相关阅读:
    几种不同风格的Toast
    [置顶] 如何访问web文件夹之外的文件
    30天自制操作系统笔记(九十)
    tomcat install on Linux
    共享内存使用的基本思路和接口
    30天自制操作系统笔记(九十)——源码
    storm单机版安装配置
    新安装XAMPP,phpMyAdmin错误:#1045
    TI-Davinci开发系列之二使用CCS5.2TI Simulator模拟环境调试DSP程序
    ffmpeg的logo, delogo滤镜参数设置
  • 原文地址:https://www.cnblogs.com/277223178dudu/p/10634808.html
Copyright © 2011-2022 走看看