gpt4 book ai didi

c++ - `x` 的所有元素是否都存在于 `y`(已排序 vector )中?

转载 作者:行者123 更新时间:2023-11-30 01:36:22 29 4
gpt4 key购买 nike

xy 是两个排序的 vector 。我想弄清楚这三个中哪个是正确的

A. All elements of `y` are present in `x`
B. Some but not all elements of `y` are present in `x`
C. No element of `y` is present in `x`
U. Undefined (because `y` is empty)

一个简单的方法是用

template<typename T>
char f(std::vector<T> x, std::vector<T> y)
{
if (y.size() == 0)
{
return 'U';
}

bool whereAnyElementFound = false;
bool whereAnyElementNotFound = false;
for (T& y_element : y)
{
bool isElementFound = std::find(x.begin(),x.end(),y_element) != x.end();
if (isElementFound)
{
whereAnyElementFound = true;
if (whereAnyElementNotFound)
{
return 'B';
}
} else
{
whereAnyElementNotFound = true;
if (whereAnyElementFound)
{
return 'B';
}
}
}
if (whereAnyElementFound)
{
return 'A';
} else if (whereAnyElementNotFound)
{
return 'C';
}
abort();
}

该函数正确地将以下输入与输出匹配

inputs: x = {1,2,4,5} y = {2,5}
output: A

inputs: x = {1,2,4,5} y = {2,7}
output: B

inputs: x = {1,2,4,5} y = {6,7}
output: C

inputs: x = {1,2,4,5} y = {}
output: U

但是,这种方法没有利用两个 vector 都已排序的事实。对于更大的 vector ,这个函数如何变得更快?

最佳答案

对于 O(N) 额外空间的成本,您可以使用 std::set_intersection .它具有 O(2(N1+N2-1)) 复杂度,并生成两个 vector 之间所有公共(public)元素的“集合”。然后,您可以检查新“集合”的大小以计算出 A、B、C 和 U。

int main()
{
std::vector<int> v1{1,2,3,4,5,6,7,8};
std::vector<int> v2{5,7,9,10};

std::vector<int> intersection;

std::set_intersection(v1.begin(), v1.end(),
v2.begin(), v2.end(),
std::back_inserter(intersection));
if (intersection.size() == v2.size() && v2.size() > 0)
std::cout << "A";
else if (intersection.size() > 0)
std::cout << "B";
else if (intersection.size() == 0 && v2.size() > 0)
std::cout << "C";
else
std::cout << "U";
}

关于c++ - `x` 的所有元素是否都存在于 `y`(已排序 vector )中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52300550/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com