【发布时间】:2014-10-19 18:45:35
【问题描述】:
从this,我们知道了解决两个排序数组交集的方法。那么如何获取多个排序数组的交集呢?
基于两个排序数组的答案,我们可以将其应用于多个数组。这是代码
vector<int> intersectionVector(vector<vector<int> > vectors){
int vec_num = vectors.size();
vector<int> vec_pos(vec_num);// hold the current position for every vector
vector<int> inter_vec; // collection of intersection elements
while (true){
int max_val = INT_MIN;
for (int index = 0; index < vec_num; ++index){
// reach the end of one array, return the intersection collection
if (vec_pos[index] == vectors[index].size()){
return inter_vec;
}
max_val = max(max_val, vectors[index].at(vec_pos[index]));
}
bool bsame = true;
for (int index = 0; index < vec_num; ++index){
while (vectors[index].at(vec_pos[index]) < max_val){
vec_pos[index]++; // advance the position of vector, once less than max value
bsame = false;
}
}
// find same element in all vectors
if (bsame){
inter_vec.push_back(vectors[0].at(vec_pos[0]));
// advance the position of all vectors
for (int index = 0; index < vec_num; ++index){
vec_pos[index]++;
}
}
}
}
有没有更好的解决方法?
更新1
从1 和2 这两个主题来看,Hash set 似乎是更有效的方法。
更新2
为了提高性能,也许可以在上面的代码中使用min-heap 代替vec_pos。变量max_val 保存所有向量的当前最大值。所以只需将根值与max_val比较,如果相同,则可以将该元素放入交集列表中。
【问题讨论】:
标签: c++ arrays algorithm sorting