【发布时间】: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<int>而不是 C 样式数组中 -
请注意,尽管链接的欺骗中接受的答案似乎并不完全正确,但看起来 lambdapilgrim 的答案是正确的,包括适用于长度不等的数组(并且 JF Sebastian 的答案显示了C++ 中的算法)。
-
lambdapilgrim 似乎有正确的答案。我通过对两个数组进行并发二进制搜索来尝试解决这个问题,但是当数组的长度不相等时,循环不变量 i + j = k 不成立,因此这种方法不起作用。
标签: c++ arrays algorithm binary-search sortedlist