【问题标题】:Most efficient way to copy elements from a vector to another, given a list of indices which are not to be copied给定不被复制的索引列表,将元素从向量复制到另一个向量的最有效方法
【发布时间】:2017-05-25 10:30:35
【问题描述】:

假设我有一个向量V = {5, 10, 2, 1, 6} 和一个list of indices= {2, 3, 0}。现在生成的数据结构U 应该包含元素{10, 6} 不一定按顺序排列。天真的方法的时间复杂度为O(n^2)。我们可以做得更好吗?

【问题讨论】:

  • list 进行预排序,然后在list 中保留一个迭代器,该迭代器已更新为指向下一个要跳过的元素。
  • 结果数据如何包含元素 {10, 6}??
  • @Null 因为从向量 V 中,元素 V[2]、V[3] 和 V[0] 不会复制到新向量中。

标签: c++ arrays list vector stl


【解决方案1】:

你可以添加一个向量大小的 bool 数组来指示是否会采用这个索引,在 O(n) 中填充这个数组,然后你可以遍历向量并选择另一个 O(n) 中的元素这将是 O(2*n) = O(n),如下所示:

#include <iostream>
#include <vector>
#include <string.h>
using namespace std;

int main (){
    vector<int> items ;
    vector<int> notIncluded ;
    items.push_back(1);
    items.push_back(2);
    items.push_back(3);
    items.push_back(5);
    notIncluded.push_back(1);
    notIncluded.push_back(0);

    vector<int> selectedItems;

    bool idx[items.size()];
    memset(idx, true, sizeof(idx));

    for(int i=0;i<notIncluded.size();i++){
        idx[notIncluded[i]] = false;
    }

    for(int i=0;i<items.size();i++){
        if(idx[i]){
            selectedItems.push_back(items[i]);
            cout << items[i] << " " ;
        }
    }

return 0;
}

【讨论】:

【解决方案2】:

我们可以在 O(nlog(n)) 中通过对索引列表进行排序,然后从向量中选择索引不在排序列表中的元素。 排序将花费 O(nlog(n)) 并且通过向量将是 O(n)

O(nlog(n))+O(n)=O(nlog(n))

【讨论】:

    猜你喜欢
    • 2012-06-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多