这是您可以用来完成任务的算法:
- 构造两个数组的并集
- 构造两个数组的交集
- 从联合中减去交集即可得到结果
Java集合支持
addAll,
removeAll和
retainAll。使用
addAll构建工会,
retainAll构建交叉,并
removeAll作减法,像这样的:
// Make the two listsList<Integer> list1 = Arrays.asList(1, 2, 3, 4);List<Integer> list2 = Arrays.asList(2, 3, 4, 6, 7);// Prepare a unionList<Integer> union = new ArrayList<Integer>(list1);union.addAll(list2);// Prepare an intersectionList<Integer> intersection = new ArrayList<Integer>(list1);intersection.retainAll(list2);// Subtract the intersection from the unionunion.removeAll(intersection);// Print the resultfor (Integer n : union) { System.out.println(n);}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)