前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >剑指offer 数组中的逆序对

剑指offer 数组中的逆序对

作者头像
week
发布2018-12-24 12:57:10
4270
发布2018-12-24 12:57:10
举报
文章被收录于专栏:用户画像用户画像

题目描述

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

输入描述:

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

数据范围:

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

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

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

示例1

输入

代码语言:javascript
复制
1,2,3,4,5,6,7,0

输出

代码语言:javascript
复制
7
代码语言:javascript
复制
public class Solution {
    private long count;
    public int InversePairs(int [] array) {
        if(array==null||array.length==0)
            return 0;
        int[] temp=new int[array.length];
        divid(array,temp,0,array.length-1);
        return (int)(count%1000000007);
    }
    public void divid(int[]array,int []temp,int low,int high){
        if(low>=high)
            return;
        int mid=(low+high)/2;
        divid(array,temp,low,mid);
        divid(array,temp,mid+1,high);
        merge(array,temp,low,high);
    }
    public void merge(int[]array,int[]temp,int low,int high){
        int lowend=(low+high)/2;
        int highpos=lowend+1;
        int temppos=low;
        int len=high-low+1;
        while(low<=lowend&&highpos<=high){
            if(array[low]<=array[highpos]){
                temp[temppos++]=array[low++];			//简化写法,节省代码
            }else{
                count+=(lowend-low+1)%1000000007;  
//改为count=count%1000000007+((middle-leftPoint+1)%1000000007);才通过
                temp[temppos++]=array[highpos++];         //简化写法,节省代码
            }
        }
        while(low<=lowend){
            temp[temppos++]=array[low++];
        }
        while(highpos<=high){
            temp[temppos++]=array[highpos++];
        }
        for(int i=len;i>0;i--,high--){					//for循环中一个分号可以写多个条件
            array[high]=temp[high];
        }
    }
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018年12月03日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 题目描述
  • 输入描述:
  • 输入
  • 输出
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档