数据结构交集并集的测试代码
时间: 2023-11-26 12:45:07 浏览: 39
以下是Python语言实现线性表交集并集的测试代码:
```
# 定义线性表A和B
A = [-2, 1, 7, 19, 26]
B = [-2, 11, 26, 50]
# 计算交集
C = list(set(A) & set(B))
print("交集为:", C)
# 计算并集
D = list(set(A) | set(B))
print("并集为:", D)
# 计算差集
E = list(set(A) - set(B))
print("差集为:", E)
```
以上代码中,我们使用Python内置的set()函数将列表转换为集合,然后使用&、|、-等符号计算交集、并集、差集。最后将结果转换为列表输出。
相关问题
数据结构求并集、交集、差集
您好,对于求并集、交集、差集,可以使用集合(Set)数据结构来实现。以下是示例代码:
// 求并集
Set<Integer> unionSet = new HashSet<>(set1);
unionSet.addAll(set2);
// 求交集
Set<Integer> intersectionSet = new HashSet<>(set1);
intersectionSet.retainAll(set2);
// 求差集
Set<Integer> differenceSet = new HashSet<>(set1);
differenceSet.removeAll(set2);
其中,set1和set2分别为两个集合。
java 集合求交集和并集的代码
求交集的代码:
```java
List<Integer> list1 = Arrays.asList(1, 2, 3, 4);
List<Integer> list2 = Arrays.asList(3, 4, 5, 6);
List<Integer> intersection = new ArrayList<>(list1);
intersection.retainAll(list2);
System.out.println(intersection); // 输出 [3, 4]
```
求并集的代码:
```java
List<Integer> list1 = Arrays.asList(1, 2, 3, 4);
List<Integer> list2 = Arrays.asList(3, 4, 5, 6);
Set<Integer> union = new HashSet<>(list1);
union.addAll(list2);
System.out.println(union); // 输出 [1, 2, 3, 4, 5, 6]
```
需要注意的是,求交集和并集的集合类型可以根据具体情况进行调整,上述代码中使用了 List 和 Set 两种不同的集合类型。