- 对向量进行排序。
- 使用
std::set_intersection() 3 次(与您拥有的向量一样多 - 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