3 回答
TA贡献1853条经验 获得超9个赞
如果您需要列表 1 中的所有内容但不需要列表 2
1) 遍历第一个列表并将每个元素添加到 HashSet。
2) 使用 set.removeAll(list2) 删除列表 2 中的所有内容。
剩余部分是 list1 中的内容,而不是 list2 中的内容。
如果您需要获取任一列表中的所有内容而不是另一个列表中的所有内容,则可以反向重复此操作。这应该将操作反转为 O(n+m),其中 n 是列表 1 的长度,m 是列表 2 的长度。您的伪代码是 O(n*m)。
HashSet firstButNotSecond = new HashSet(list1);
firstButNotSecond.removeAll(list2);
HashSet secondButNotFirst = new HashSet(list2);
secondButNotFirst.removeAll(list1);
TA贡献1875条经验 获得超3个赞
ArrayList<String> list2 = new ArrayList();
list2.add("AB");
list2.add("BA");
ArrayList<String> list1 = new ArrayList();
list1.add("AB");
list1.add("BA");
list1.add("C");
//remove all the element from the list1 which are also in list2
list1.removeAll(list2);
System.out.println("Result: " + list1); //only C will left behind
添加回答
举报