- 排序的矢量。
- 使用
std::set_intersection()
三次(你有儘可能多的載體 - 1)。
時間複雜度分析:
- 4 * O(nlogn)= O(nlogn)在2 *(firstSize + secondSize)
- 線性 - 1
- 線性在2 *(firstSecondInterSize + thirdSize) - 1
- 線性2 *(firstSecondThirdInterSize + fourthSize) - 1
其由O(nlogn)爲界,這意味着排序是該算法的瓶頸。
完整代碼例如:
#include <iostream> // std::cout
#include <algorithm> // std::set_intersection, std::sort
#include <vector> // std::vector
int main() {
std::vector<int> first = {5,10,15,20,25};
std::vector<int> second = {50,40,30,20,10};
std::vector<int> third = {10,20,3,4,0};
std::vector<int> fourth = {4,20,10,3,6};
std::vector<int> v(first.size() + second.size() + third.size() + fourth.size());
std::vector<int>::iterator it;
std::sort (first.begin(),first.end());
std::sort (second.begin(),second.end());
std::sort (third.begin(),third.end());
std::sort (fourth.begin(),fourth.end());
it=std::set_intersection (first.begin(), first.end(), second.begin(), second.end(), v.begin());
it=std::set_intersection (v.begin(), v.end(), third.begin(), third.end(), v.begin());
it=std::set_intersection (v.begin(), v.end(), fourth.begin(), fourth.end(), v.begin());
v.resize(it-v.begin());
std::cout << "The intersection has " << (v.size()) << " elements: ";
for (it=v.begin(); it!=v.end(); ++it)
std::cout << ' ' << *it;
std::cout << '\n';
return 0;
}
輸出:
的交點有2個要素:10 20
也許窺視['的std :: set_intersection'] (http://en.cppreference.com/w/cpp/algorithm/set_intersection) – Mark
既然你有兩個以上,[this](https: //stackoverflow.com/questions/12875993/efficient-set-intersection-of-a-collection-of-sets-in-c)可能更相關。 – Mark