我在接受采访时被问及这是我提供的解决方案:
public static int[] merge(int[] a, int[] b) {
int[] answer = new int[a.length + b.length];
int i = 0, j = 0, k = 0;
while (i < a.length && j < b.length)
{
if (a[i] < b[j])
{
answer[k] = a[i];
i++;
}
else
{
answer[k] = b[j];
j++;
}
k++;
}
while (i < a.length)
{
answer[k] = a[i];
i++;
k++;
}
while (j < b.length)
{
answer[k] = b[j];
j++;
k++;
}
return answer;
}
Run Code Online (Sandbox Code Playgroud)
有没有更有效的方法来做到这一点? …
在C++中交叉两个集合的标准方法是执行以下操作:
std::set<int> set_1; // With some elements
std::set<int> set_2; // With some other elements
std::set<int> the_intersection; // Destination of intersect
std::set_intersection(set_1.begin(), set_1.end(), set_2.begin(), set_2.end(), std::inserter(the_intersection, the_intersection.end()));
Run Code Online (Sandbox Code Playgroud)
我该怎么做一个就地设置交叉点?也就是说,我希望set_1具有对set_intersection的调用结果.显然,我可以做一个set_1.swap(the_intersection),但这比现场交叉效率要低得多.
我有两个unordered_set并想要它们的交集。我找不到执行此操作的库函数。
本质上,我想要的是:
unordered_set<int> a = {1, 2, 3};
unordered_set<int> b = {2, 4, 1};
unordered_set<int> c = a.intersect(b); // Should be {1, 2}
Run Code Online (Sandbox Code Playgroud)
我可以做类似的事情
unordered_set<int> c;
for (int element : a) {
if (b.count(element) > 0) {
c.insert(element);
}
}
Run Code Online (Sandbox Code Playgroud)
但我认为应该有更方便的方法吗?如果没有,有人可以解释为什么吗?我知道有set_intersection,但这似乎只对向量起作用?
谢谢