数组中的逆序对

来源:互联网 发布:全国城市 首字母 json 编辑:程序博客网 时间:2024/04/28 06:01

题目描述
在数组中的两个数字,如果前面一个数字大于后面的数字,则这两个数字组成一个逆序对。输入一个数组,求出这个数组中的逆序对的总数。
http://www.nowcoder.com/practice/96bd6684e04a44eb80e6a68efc0ec6c5?rp=2&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking
假如可以把这个数组分为两个有序数组a和b,如果a中的一个元素a[i]比b中的一个元素b[j]大,那么在数组a中,排在元素a[i]之后的所有元素都比b[j]大,及都是逆序对。通过这种方法,可以很方便的统计出所有的逆序对。而这,正好是归并排序的思想。借助于归并排序,可以很好的完成这道题目。不得不吐槽的是,牛客网给出的数据规模非常的小,用纯暴力的方法也可以通过。
归并排序是一种递归分治的思想。它将数组分为有序的两组a、b,为了让a、b有序,将这个两组再各自分为两组。一次类推,直到每组都只有一个元素,就认为该组有序。然后再将相邻的两个小组合并起来。由于把一个数组分为n组,需要logN步,每一步都要合并有序数组,时间复杂度为O(N),所以时间复杂度为O(N*logN)。

 public int InversePairs(int [] array) {        int n = array.length;        int temp[] = new int[n];        if (n <= 1)            return 0;        return mergeSort(array, 0, n - 1, temp);    }public int mergeSort(int a[], int first, int last, int temp[]) {        int count = 0;        if (first < last) {            int mid = (first + last) / 2;            count += mergeSort(a, first, mid, temp); // 左边有序            count += mergeSort(a, mid + 1, last, temp); // 右边有序            count += mergeArray(a, first, mid, last, temp); // 将两个有序数组合并        }        return count;}  public int mergeArray(int a[], int first, int mid, int last, int temp[]) {        // 将两个有序数组a[first……mid],a[mid……last]合并。        int i = first, j = mid + 1;        int m = mid, n = last;        int k = 0;        int count = 0;        while (i <= m && j <= n) {            if (a[i] <= a[j])                temp[k++] = a[i++];            else {                temp[k++] = a[j++];                count += mid - i + 1;            }        }        while (i <= m)            temp[k++] = a[i++];        while (j <= n)            temp[k++] = a[j++];        for (i = 0; i < k; i++)            a[first + i] = temp[i];        return count;    }
0 0