【问题标题】:Kth Ranked Element Among 2 Unsorted Arrays2个未排序数组中的第K个排序元素
【发布时间】:2016-04-06 10:24:52
【问题描述】:

假设我们有两个数组 A[] 和 B[]。每个数组包含 n 个未排序的不同整数。我们需要以最有效的方式在 2 个数组的并集中找到第 k 个排名元素。 (请不要发布有关合并数组然后对其进行排序以返回合并数组中的第 k 个索引的答案)

【问题讨论】:

  • 区别在于它们是唯一的,例如 A[8 3 2 4 12] 和 B[6 11 1 5 9]。所有元素都是小于 10000000 的整数,并且元素不必是连续的。
  • 这只是一个例子。我们需要解决未排序数组的一般情况。我已更新评论以避免任何混淆。

标签: c arrays algorithm data-structures


【解决方案1】:

您可以使用selection algorithm 在 O(N) 时间内找到第 K 个项目,其中 N 是数组大小的总和。显然,您将这两个数组视为一个大数组。

【讨论】:

  • 我知道这种方法,但我需要更复杂的方法
  • 在未排序列表中查找第 K 个项目没有比 O(N) 更好的复杂度了。
【解决方案2】:

数组的联合可以在线性时间内完成。我跳过了那部分。

您可以使用quick sort 中使用的partition() 算法。在快速排序中,该函数必须递归两个分支。然而,这里我们只是有条件地调用递归调用,因此只有 1 分支递归。

主要概念partition() 将选择的PIVOT 元素放置在其适当的排序位置。因此,我们可以使用这个属性来选择我们感兴趣的数组的那一半,然后在那一半上递归。这将阻止我们对整个数组进行排序。

我根据上述概念编写了以下代码。假设 rank = 0 意味着数组中的最小元素。

void swap (int *a, int *b)
{
    int tmp = *a;
    *a = *b;
    *b = tmp;
}

int partition (int a[], int start, int end)
{
    /* choose a fixed pivot for now */
    int pivot = a[end];
    int i = start, j;

    for (j = start; j <= end-1; j++) {
        if (a[j] < pivot) {
            swap (&a[i], &a[j]);
            i++;
        }
    } 
    /* Now swap the ith element with the pivot */
    swap (&a[i], &a[end]);
    return i;
}

int find_k_rank (int a[], int start, int end, int k)
{
    int x = partition (a, start, end);
    if (x == k) {
        return a[x];
    } else if (k < x) {
        return  find_k_rank (a, start, x-1, k);
    } else {
        return find_k_rank (a, x+1, end, k);
    }
}

int main()
{
    int a[] = {10,2,7,4,8,3,1,5,9,6};
    int N = 10;
    int rank = 3;
    printf ("%d\n", find_k_rank (a, 0, N-1, rank));
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-05
    • 2017-03-04
    • 1970-01-01
    • 2016-10-23
    相关资源
    最近更新 更多