c语言数组交集,c-多个排序数组的交集

从this开始,我们知道了解决两个排序数组相交的方法.那么如何获得多个排序数组的交集呢?

基于两个排序数组的答案,我们可以将其应用于多个数组.这是代码

vector intersectionVector(vector > vectors){

int vec_num = vectors.size();

vector vec_pos(vec_num);// hold the current position for every vector

vector 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]++;

}

}

}

}

有更好的解决方法吗?

UPDATE1

从这两个主题1和2看来,哈希集是一种更有效的方法.

UPDATE2

为了提高性能,可以在上面的代码中使用min-heap代替vec_pos.变量max_val保留所有向量的当前最大值.因此,只需将根值与max_val进行比较,如果它们相同,则可以将该元素放入交集列表中.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值