雜湊 4 求兩個鍊錶的交集以及並集

2021-07-03 06:45:44 字數 1657 閱讀 4706

目錄

1.簡單方法

2.使用歸併排序

3.使用雜湊

給定兩個鍊錶,求它們的交集(intersection)以及並集(union)。用於輸出的list中的元素順序可不予考慮。

例子:輸入下面兩個鍊錶:

list1: 10->15->4->20

list2: 8->4->2->10

輸出鍊錶:

交集list: 4->10

並集list: 2->8->20->4->15->10

可以參考鍊錶系列中的"鍊錶操作 - 求兩個鍊錶的交集(intersection)以及並集(union)"

可以參考鍊錶系列中的"鍊錶操作 - 求兩個鍊錶的交集(intersection)以及並集(union)"

calculateunion (list1, list2),求鍊錶的並集的演算法:

將result list初始化為null,然後建立乙個空的雜湊表。依次遍歷這兩個鍊錶,對於其中的每個元素,在雜湊表中進行查詢。如果元素不在雜湊表中,則將其插入到result list中,並插入到雜湊表中。如果元素已經存在於雜湊表中,則忽略它。

calculateintersection (list1, list2),求鍊錶的交集的演算法:

將result list初始化為null,然後建立乙個空的雜湊表。 遍歷list1, 對於其中的每個元素,將其插入到雜湊表中。然後遍歷list2, 對於其中的每個元素,在雜湊表中進行查詢。如果元素已經存在於雜湊表中,則插入到result list中。如果元素不在雜湊表中,則忽略它。

上面的這兩個方法,即使list中存在重複的元素,也能處理。

時間複雜度:方法3的時間複雜度取決於所使用的雜湊方法,以及輸入鍊錶中的元素分布。在實際的情況中,方法3可能比前面的兩種方法更好。

**如下:

#include#include#include#includevoid calculateunion(const std::list& list1, const std::list& list2, std::list& outputresult) 

for (auto iter : list2)

//convert map to list

for (auto iter : tmp)

}void calculateintersection(const std::list& list1, const std::list& list2, std::list& outputresult)

for (auto iter : list2)

}int main() );

result.clear();

calculateintersection(list1, list2, result);

std::cout << "\nintersection result: \n";

std::for_each(result.begin(), result.end(), (const int& value) );

std::cout << std::endl;

return 0;

}

執行結果:

union result:

2 4 8 10 15 20

intersection result:

4 10

求兩個鍊錶的並集

這學期剛剛學的資料結構 老師布置的作業 寫寫看。include include define len sizeof struct list struct list struct list creat 定義函式,此函式返回乙個指向煉表頭的指標 p2 next null return head 判斷第b...

求兩個List的交集和並集

最近遇到的面試題,假設有兩個list分別為list1和list2 交集 list1.retainall list2 list1的資料就變成list1和list2的交集,list2不變。public class listtest system.out.println for int i 0 i lis...

求兩個集合的交集和並集

交集 用兩個指標分別指向兩個陣列的頭部。如果其中乙個元素比另乙個小,後移小的那個陣列的指標 如果相等,那麼把該元素新增到交集裡,同時後移兩個陣列的指標。一直這樣操作下去,直到有乙個指標超過陣列範圍。public list intersection int a,int b else return re...