LintCode:532 逆序对

题目:


分析:

方法一:找出所有的数对,在判断它们是否为逆序对,时间复杂度为O(n^2),因此很可能不能通过。

public long reversePairs(int[] A) {
        // write your code here
        long count=0;
        for(int i=0;i<A.length-1;i++){
            for(int j=i+1;j<A.length;j++){
                if(A[i]>A[j])   count++;
            }
        }
        return count;
    }

方法二:采用归并排序的思想来统计逆序对的个数,合并两部分子数组的时候,如1,3,5,7,9,2,4,6,8时,low=1,high=8,mid=9,i=3,j=2时,则包括3在内的3,5,7,9都能与2构成逆序对,因为左半部分数组是递增有序的,所以构成逆序对的个数为mid-i+1。

//使用归并排序
    public long reversePairs1(int[] A) {
        if(A==null || A.length==0)  return 0;
        return mergesort(A,0,A.length-1);
    }

    public long mergesort(int[] A,int low, int high){
        long count=0;
        if(low==high)   return 0;
        else{
            int mid=(low+high)/2;
            count+=mergesort(A,low,mid);
            count+=mergesort(A,mid+1,high);
            count+=MergeTwoData(A,low,mid,high);
        }
        return count;
    }

    public long MergeTwoData(int[] A,int low,int mid,int high){
        long count=0;
        int[] arr=new int[high-low+1];
        int i=low; int m=mid;
        int j=mid+1; int n=high;
        int index=0;
        while(i<=m && j<=n){
            if(A[i]<=A[j])
                arr[index++]=A[i++];
            else{
                arr[index++]=A[j++];
                count+=mid-i+1;
            }
        }
        while(i<=m) {
            arr[index++] = A[i++];
        }
        while(j<=n) {
            arr[index++] = A[j++];
        }
        //写回原数组
        int k=0;
        for(int o=low;o<=high;o++)
            A[o]=arr[k++];
        return count;
    }

猜你喜欢

转载自blog.csdn.net/qq_27139155/article/details/79950093