【问题标题】:How to find the kth largest number in two sorted arrays of different sizes [duplicate]如何在两个不同大小的排序数组中找到第k大的数[重复]
【发布时间】:2014-07-12 06:26:43
【问题描述】:

这与An algorithm to find the nth largest number in two arrays of size n 的问题相同,只是两个排序后的数组大小不同。

我尝试实现一个类似于建议的算法版本来解决我的问题,但我无法证明它的正确性。 k = 6 时似乎失败了。当算法完成时,返回的对分别是 list1 和 list2 的索引。

#include <iostream>
#include <utility>

using namespace std;

pair<int, int> smallestKElements(int list1[], int list2[], int k) {

// TODO: pass in the array sizes as parameters 
int m = 8; 
int n = 5;

// initialize array pointers such that i + j = k
int i = m/2;
int j = n/2; 
if (i + j + 2 < k) {
    while (i + j + 2 != k) {
        if (++i + j + 2 == k)
            break;
        if (i + ++j + 2 == k)
            break;
    }
} else if (i + j + 2 > k) {
    while (i + j + 2 != k) {
        if (--i + j + 2 == k)
            break;
        if (i + --j + 2 == k)
            break;
    }
}

// step forward in one array and step backward in another array
// decrement step size with every iteration until it is 0
int s = k/2; 
while (s > 0) {
    if (list1[i] < list2[j]) {
        if (m - 1 - i >= s &&
            j >= s) {

            i += s;
            j -= s;
        }
    } else {
        if (i >= s &&
            n - 1 - j >= s) {

            i -= s;
            j += s;
        }
    }
    s = s/2;
}

pair<int, int> r(i,j);
return r;
}

int main() {

int list1[] = {1, 4, 6, 7, 10, 11, 13, 27};
int list2[] = {2, 3, 20, 40, 60};

pair<int, int> test = smallestKElements(list1, list2, 6);
cout << test.first << "," << test.second << endl;

return 0;
}

【问题讨论】:

  • 你能添加一些你的算法的文字解释吗?我还没有完全消化它,但它看起来不像我会使用的东西。
  • 要修复你的“TODO”,将项目保存在 vector&lt;int&gt; 而不是 C 样式数组中
  • 请注意,尽管链接的欺骗中接受的答案似乎并不完全正确,但看起来 lambdapilgrim 的答案是正确的,包括适用于长度不等的数组(并且 JF Sebastian 的答案显示了C++ 中的算法)。
  • lambdapilgrim 似乎有正确的答案。我通过对两个数组进行并发二进制搜索来尝试解决这个问题,但是当数组的长度不相等时,循环不变量 i + j = k 不成立,因此这种方法不起作用。

标签: c++ arrays algorithm binary-search sortedlist


【解决方案1】:

好的,如果我理解您的问题,您可以为每个列表执行类似的操作:

std::nth_element(lst, lst + k, begin(lst) + list_size, std::greater<int>());

请记住,您需要列表的大小。 您可以对另一个数组执行相同的操作。这将修改数组,如果您不想修改数组,请制作 std::reference_wrapper 和 nth_element 的数组。

【讨论】:

  • 我对实现很好奇。
  • 实际上,我不确定是否能正确回答您的问题。您需要在两个数组中查找第 n 个最大的元素。还是每个数组中最大的?
  • 如果你想要的是一个原始的实现,那现在工作量太大了。我正在工作,目前无法为您提供帮助。
  • 该实现对元素进行排序,并使用比较器将位于第 n 个位置的元素。在这种情况下,该元素之前的所有元素都大于或等于第 n 个元素。之后的所有内容都小于第 n 个元素。
  • 我正在寻找查看两个数组的第 n 个最大元素。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-03-04
  • 1970-01-01
  • 2015-11-26
  • 2014-06-07
  • 2020-12-02
相关资源
最近更新 更多