我有两个向量:
std::vector<int> V1 {1,2,3,4,5,6,7};
std::vector<int> V2 {1,2,3};
执行以下操作会导致二次运行时复杂性:
for(auto IT = V1.begin(); IT != V1.end(), IT++)
{
for(auto IT2 = V2.begin(); IT2 != V2.end(); IT2++)
{
if(*IT == *IT2){std::cout<<"Found a match!"<<std::endl;}
else{std::cout<<"No match!"<<std::endl;}
}
}
有没有明确的方法将其降低到线性时间?
使用STL算法会启用吗?
例如:
for(auto IT = V1.begin(); IT != V1.end(); IT++)
{
std::find(V2.begin(), V2.end(), *IT);
}
答案 0 :(得分:2)
您需要在线性时间保留一个数组(您的源数组,因为您显然正在搜索它的第0个第n个元素)。
但是,您可以通过确保首先对搜索空间的内容进行排序来降低其他搜索字词。这将允许使用log(n)复杂度的二进制搜索算法。
祝你好运!这方面的一个例子:
std::vector<int> V1 {1,4,5,6,3};
std::vector<int> V2 {100, 104,101,3};
bool condition {false};
std::sort(V2.begin(), V2.end());
for(auto IT = V1.begin(); IT != V1.end(); IT++)
{
auto result {std::binary_search(V2.begin(), V2.end(), *IT)};
if(result > 0){ condition = true};
}