计数阵列号对索引的总数,使得改编[1] - ; ARR [J]和I< Ĵ [英] Count total number pairs of indices in array such that arr[i] < arr[j] and i < j

查看:112
本文介绍了计数阵列号对索引的总数,使得改编[1] - ; ARR [J]和I< Ĵ的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了问这个<一href="http://stackoverflow.com/questions/13791288/count-all-pairs-of-indices-in-array-such-that-arri-arrj">here但因为我忘了提及对指数的条件下,创造了新的问题。

Meant to ask this here but since I forgot to mention the condition on the indices, creating a new question.

现在的问题是给予排序的数组,找到对指数 I,J ,使得总数I&LT; Ĵ改编[1] - ; ARR [J] 。复杂性应该是线性的或接近它。

The question is given an unsorted array, find the total number of pairs of indices i, j such that i < j and arr[i] < arr[j]. Complexity should be linear or as close to it.

推荐答案

如果目标是要找到对 I&LT数量; Ĵ,使得改编[1] - GT;改编[j]的,这将是反转计数,可通过合并排序阵列和计数多少值的每个项目被移动过去被确定。

If the target were to find the number of pairs i < j such that arr[i] > arr[j], it would be the inversion count, that can be determined by merge-sorting the array and counting how many values each item is moved past.

在这里,我们可以做同样的,如果我们按降序排序。

Here, we can do the same, if we sort in descending order.

int pairs_count(int[] arr, int lo, int hi) {
    if (hi <= lo) return 0;
    int mid = (lo+hi)/2;
    int count = pairs_count(arr, lo, mid);
    count += pairs_count(arr, mid+1,hi);
    count += merge(arr, lo, mid, hi);
    return count;
}

int merge(int[] arr, int lo, int mid, int hi) {
    int[] scratch = new int[hi-lo+1];
    int l = lo, r = mid+1, k = 0, count = 0;
    while(l <= mid && r <= hi) {
        if (arr[r] > arr[l]) {
            scratch[k++] = arr[r++];
            count += mid-l+1;
        } else {
            scratch[k++] = arr[l++];
        }
    }
    while(l <= mid) {
        scratch[k++] = arr[l++];
    }
    while(r <= hi) {
        scratch[k++] = arr[r++];
    }
    for(k = 0; k < scratch.length; ++k) {
        arr[lo+k] = scratch[k];
    }
    retrun count;
}

这篇关于计数阵列号对索引的总数,使得改编[1] - ; ARR [J]和I&LT; Ĵ的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆