leetcode | 数组中的逆序对

在数组中的两个数字,如果前面一个数字大于后面的数字,则这两个数字组成一个逆序对。输入一个数组,求出这个数组中的逆序对的总数。

主要是以归并排序的思想

public class Solution {
    public  int InversePairs(int [] array) {
        if (array==null) return 0;
        if (array.length<2) return 0;
        int[] copy = new int[array.length];
        return merge(array,0,array.length-1,copy);
    }

    public int mergeArray(int[] a,int l,int m,int h,int[] tmp)
    {
        int count = 0;
        int i = l;
        int j = m+1;
        int k = l;
        while(i<=m&&j<=h)
        {
            if(a[i]>a[j])
            {
                tmp[k++] = a[j++];
                count += m-i+1;
            }
            else
                tmp[k++] = a[i++];
        }
        while(i<=m)
        {
            tmp[k++] = a[i++];
        }
        while(j<=h)
        {
            tmp[k++] = a[j++];
        }
        for (int p = l; p <= h; p++) {
            a[p] = tmp[p];
        }
        return count;

    }

    public int merge(int[] a,int l,int h,int[] temp)
    {
        int count = 0;
        if(l


你可能感兴趣的:(牛客网)