码迷,mamicode.com
首页 > 编程语言 > 详细

剑指offer: 数组中的逆序对

时间:2017-09-13 23:22:48      阅读:208      评论:0      收藏:0      [点我收藏+]

标签:return   介绍   存在   tar   个数   img   code   ges   思路   

1. 最简单的思路,对每个值,遍历与其逆序的数组对;但时间复杂度太高;

2. 归并排序的思路:

先将数组分隔成子数组,先统计出子数组内的逆序对的数目,然后统计两个相邻子数组之间的逆序对的数目;

 

技术分享

 

 

 

    int InversePairsCore(int *data, int * copy, int start, int end)
    {
        //递归介绍条件,只剩一个元素
        if(start==end)
        {
            copy[start]=data[start];
            return 0;
        }
        int length=(end-start)/2;
        int left=InversePairsCore(copy, data, start, start+length);
        int right=InversePairsCore(copy,data, start+length+1,end);
        int i=start+length;//前半段最后一个数字的下标
        int j=end;// 后半段最后一个下标
        int indexCopy=end;
        int count=0;
        while(i>=start&& j>=start+length+1)
        {
            if(data[i]>data[j])
            {
                copy[indexCopy--]=data[i--];
                count+=j-start-length;//右侧有j-start-length个元素,小于data[i]
              if(count>=1000000007)
                count%=1000000007;
            }
            else
            {

                copy[indexCopy--]=data[j--];//右侧元素大,,不存在逆序
            }

        }

        for(;i>=start;i--)
        {
            copy[indexCopy--]=data[i];
        }
        for(;j>=start+length+1;j--)
        {
            copy[indexCopy--]=data[j];
        }
        return (left+right+count)%1000000007;
    }

    int InversePairs(int* data, int length)
    {

        if(data==NULL||length<0)
        return 0;
        int * copy=new int[length];
        for(int i=0;i<length;++i)
        copy[i]=data[i];
        int count=InversePairsCore(data, copy,0, length-1);
        delete [] copy;
        return count;
    }

 

剑指offer: 数组中的逆序对

标签:return   介绍   存在   tar   个数   img   code   ges   思路   

原文地址:http://www.cnblogs.com/fanhaha/p/7518027.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!