2015-06-19 50 views
1

我有載體,我想檢索一個載體,其中包含所有輸入向量中不重複的所有條目。踢出載體中的重複條目

#include <vector> 
int main() { 

    std::vector<int> a = {2, 1, 3}; 
    std::vector<int> b = {99, 1, 3, 5, 4}; 
    std::vector<int> c = {5, 6, 7, 1}; 

    // magic to retrieve {2, 99, 4, 6, 7} (order doesn't matter) 

} 

是否有庫函數可以幫助有效執行此任務?

我沒有綁定使用向量。解決方案可能包括列表,集合或任何最適合該任務的內容。

+0

這並不解決任務。如果一個條目出現不止一次,我希望完全踢掉它。 –

+0

你還沒有告訴是否可以使用O(N)空間來完成這個任務。如果沒有問題,那麼你可以先把所有的元素放入unorderd_map中,然後把數量等於1的元素放入矢量 –

+0

@NicoSchlömer爲什麼99在結果序列中不存在? –

回答

1

使用unordered_map,O(N),空間複雜度和O(N)的時間複雜度:

#include <vector> 
#include <unordered_map> 
#include <iostream> 

std::vector<int> 
get_unique_values(std::initializer_list<std::vector<int>> vectors) 
{ 
    std::unordered_map<int, size_t> tmp; 
    auto insert_value_in_tmp = [&tmp](int v) { 
    auto i = tmp.find(v); 
    if (i == tmp.end()) 
     tmp[v] = 1; 
    else if (i->second != 2) 
     i->second = 2; 
    }; 

    for (auto& vec : vectors) { 
    for (auto vec_value : vec) { 
     insert_value_in_tmp(vec_value); 
    } 
    } 

    std::vector<int> result; 
    for (auto v : tmp) { 
    if (v.second == 1) 
     result.push_back(v.first); 
    } 

    return result; 
}; 

int main() { 

    std::vector<int> a = {2, 1, 3}; 
    std::vector<int> b = {99, 3, 5, 4}; 
    std::vector<int> c = {5, 6, 7}; 

    std::vector<int> result = get_unique_values({a,b,c}); 

    for (auto v : result) { 
    std::cout << v << " "; 
    } 
    std::cout << '\n'; 

    return 0; 
}