简体   繁体   English

在Java中的两个列表中找到第一个列表中的唯一元素

[英]Find unique elements in the first list from two lists in Java

I am trying to find unique elements in a main list by comparing it with another list with a time complexity better than O(mn). 我试图通过将它与另一个列表的时间复杂度优于O(mn)的列表进行比较来在主列表中查找唯一元素。 Ex:- 例如:-

listA, listB . I want to get unique elements only in listA and add to a new list.

Here is what I did 这是我所做的

for (String item : listA) {
 if (!listB.contains(item)) {
   newList.add(item)
 }
}

Here the time complexity is O(mn). 在这里,时间复杂度为O(mn)。 Can anyone help me get to a better solution? 谁能帮助我找到更好的解决方案?

Set<String> setB = new HashSet<>(listB);
for (String item : listA) {
 if (!setB.contains(item)) {
    newList.add(item);
 }
}

Like @Andy Turner suggested. 就像@Andy Turner建议的那样。 Here , Set.contains Time Complexity is O(1). 在这里,Set.contains时间复杂度为O(1)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM