c++ - Kick out duplicate entries across vectors -
i have vectors , retrieve 1 vector contains entries aren't duplicated anywhere in input vectors.
#include <vector> int main() { std::vector<int> = {2, 1, 3}; std::vector<int> b = {99, 1, 3, 5, 4}; std::vector<int> c = {5, 6, 7, 1}; // magic retrieve {2, 99, 4, 6, 7} (order doesn't matter) }
is there library function can performing task efficiently?
i'm not tied using vectors. solution include lists, sets, or whatever appropriate task.
using unordered_map, o(n) space complexity , o(n) time complexity:
#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 = tmp.find(v); if (i == tmp.end()) tmp[v] = 1; else if (i->second != 2) i->second = 2; }; ( auto& vec : vectors) { ( auto vec_value : vec ) { insert_value_in_tmp(vec_value); } } std::vector<int> result; (auto v : tmp) { if (v.second == 1) result.push_back(v.first); } return result; }; int main() { std::vector<int> = {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}); (auto v : result) { std::cout << v << " "; } std::cout << '\n'; return 0; }
Comments
Post a Comment