c++ - 嵌套循环导致复杂性效率降低?

标签 c++ loops time-complexity big-o

我编写了一个简单的函数,它根据另一个 vector (V1) 的值从一个 vector (V2) 中删除元素:

std::vector<int> V1={6,2,3,4};
std::vector<int> V2={9,4,8,6,7};

for(int i=0; i<V1.size(); i++)
{
   if(!V2.empty())
   {
     V2.erase(std::remove(V2.begin(),V2.end(),V1[i]),V2.end());
   }
}

我的挑战是上述需要复杂度为 O(n)。目前这是 O(n*m),n 是 V1,m 是 V2。

注意数组不能也不能排序,因为元素的原始索引值是必需的。

问题:

  1. 我说“V2.erase”阻止此函数变为 O(n) 是否正确? (因为它是 for 循环中的嵌套迭代)。

  2. 有没有办法通过在循环外执行删除操作来解决这个问题?

最佳答案

为什么不使用 std::set_difference :

std::vector<int> test(
    std::vector<int> v1,
    std::vector<int>& v2)
{
    // The algorithm we use requires the ranges to be sorted:
    std::sort (v1.begin(), v1.end());
    std::sort (v2.begin(), v2.end());

    // our output vector: reserve space to avoid copying:
    std::vector<int> v3;
    v3.reserve (v2.size());

    // Use std::set_difference to copy the elements from
    // v2 that are not in v1 into v3:
    std::set_difference (
        v2.begin(), v2.end(),
        v1.begin(), v1.end(),
        std::back_inserter(v3));

    return v3;
}

如果 v1.size() == nv2.size() == m 运行时间大致为:

O(NlogN) + O(MlogM) + 2 O(M+N-1)


好的,那么这个怎么样:

void test2(
    std::vector<int> v1,
    std::vector<int> v2)
{
    // We can still sort this without affecting the indices
    // in v2:
    std::sort (v1.begin(), v1.end());

    // Replace all the elements in v1 which appear in v2
    // with -1:
    std::replace_if (v2.begin(), v2.end(),
        [&v1] (int v)
        {
            return std::binary_search(v1.begin(), v1.end(), v);
        }, -1);
}

非线性;估计复杂性留给 OP 练习。


第三种选择是这样的:

void test3(
    std::vector<int> v1,
    std::vector<int>& v2)
{
    // We can still sort this without affecting the indices
    // in v2:
    std::sort (v1.begin(), v1.end());

    auto ret = std::stable_partition (
        v2.begin(), v2.end(),
        [&v1] (int v)
        {
            return !std::binary_search(v1.begin(), v1.end(), v);
        });

    v2.erase (ret, v2.end());
}

同样,不是线性的,而是选项...

关于c++ - 嵌套循环导致复杂性效率降低?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40102312/

相关文章:

python - 为什么子列表在 for 循环中是可变的?

lisp - cdr的时间分析

c - 代码 θ(nLogn) 的时间复杂度如何?

PHP OpenDir 与 array_rand

python - 用于导出 C++ 的 vgg16 keras 保存模型

c++ - QPlainTextEdit 一行有多种颜色

ruby-on-rails - 如何在 Rails View 中循环并打印多维数组?

c++ - 在 Windbg 中,当抛出特定的 C++ 异常时,我可以跳过中断吗?

c++ - 如何将 SDL_Color 存储在 C++ 数组中?

node.js - 如何运行一个在循环中提取数据并在循环结束时获取数据的函数?