题解 | #NC118 数组中的逆序对 Java版

数组中的逆序对

http://www.nowcoder.com/practice/96bd6684e04a44eb80e6a68efc0ec6c5

NC118 数组中的逆序对 Java版

  1. 暴利破解肯定超时
  2. 本题考查的是排序 直接归并最省时间 话不多说直接上代码

图片说明

public class Solution {
    static int mod = (int) 1e9 + 7;
    static int count = 0;

    public int InversePairs(int [] array) {
         if (array == null || array.length == 0) {
            return 0;
        }
        sort(array, 0, array.length - 1);
        return count;
    }

    public static int[] sort(int[] a,int low,int high){
        int mid = (low+high)/2;
        if(low<high){
            sort(a,low,mid);//分成两个子序列,分别递归排序
            sort(a,mid+1,high);
            //左右归并
            merge(a,low,mid,high);
        }
        return a;
    }
    //将两个有序表合并成一个有序表
   public  static void  merge(int[] a, int low, int mid, int high) {
        int[] temp = new int[high-low+1];//定义一个数组
        int i= low;
        int j = mid+1;
        int k=0;
        // 把较小的数先移到新数组中
        while(i<=mid && j<=high){
            if(a[i]<a[j]){
               temp[k++] = a[i++];
            }else{
               count = (count + mid - i + 1) % mod;
               temp[k++] = a[j++];
            }
        }
        // 把左边剩余的数移入数组 
        while(i<=mid){
            temp[k++] = a[i++];
        }
        // 把右边边剩余的数移入数组
        while(j<=high){
            temp[k++] = a[j++];
        }
        // 把新数组中的数覆盖nums数组
        for(int x=0;x<temp.length;x++){
          a[x+low] = temp[x];//原数组从low开始的
        }
    } 
}
全部评论

相关推荐

09-23 17:42
门头沟学院 Java
兄弟们我绷不住了,小米要求10月份参加编程考试,20级以下(王腾好像21),正式和外包都得去,还要部门大排名,一巴掌给我抽象的回到大学
flex*1022:雷:我们想了很久,到底怎么样才能让用户满意,让工程师保持手感,经过长达180天的思考,我连夜睡服高管,决定发起内部考试,以编程为主
投递小米集团等公司10个岗位
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务