java - 检查多个列表中公共(public)元素的最佳方法?

标签 java algorithm performance optimization iteration

我明白 ArrayList<>的搜索速度最快( O(1)O(n) )和 LinkedList<>的插入和删除速度最快( O(1)O(n) )。

我的问题是,如果结合使用这两者,检查多个列表 (>2) 中常见元素的最佳方法是什么?

当前方法 使用三个列表和迭代方法:

out:
for(int a = 0; a < list1.size(); a++) {
    for(int b = 0; b < list2.size(); b++) {
        for(int c = 0; c < list3.size(); c++) {
            if(list1.get(a) == list2.get(b) && list1.get(a) == list3.get(c) ) {
                System.out.println(list1.get(a)); // list2.get(b) or list3.get(c) could have been subbed
                break out;
            }
        }
    } 
}

如何优化以提高效率?


编辑

感谢许多有用的回复:) 我发现最好的方法是使用列表 .retainAll()功能。

同样,为了找到三个列表之间的共同元素,我改进了下面的方法。

list1.retainAll(list2);
list1.retainAll(list3);
for(int i : list1) {
    System.out.println(i);
}

最佳答案

假设元素实现hashCode,您可以获得与所有列表中的元素数量成线性关系的预期时间:

public static <T> Set<T> commonElements(List<? extends T> list1, List<? extends T>... lists) {
    // use LinkedList for efficient delete operation
    // make sure elements are distinct to not check the same element multiple times
    List<T> commonElements = new LinkedList<>(new HashSet<>(list1));
    for (List<? extends T> l : lists) {
        // use HashSet for fast contains check
        // keep only elements in the list
        commonElements.retainAll(new HashSet<>(l));
    }
    return new HashSet<>(commonElements);
}

这比您的方法更快,因为 HashSet 允许在 O(1) 预期时间内查找。

请注意,对于较小的输入列表,这种方法的性能可能会更差。

关于java - 检查多个列表中公共(public)元素的最佳方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38783471/

相关文章:

algorithm - 如果 m<n,O(n+m) 和 O(n) 符号是否等效?

performance - 存储过程执行时间不正确

java - 媒体播放器和服务类

java - JFileChooser 将无法正常工作

arrays - 检查两个数组是否相等的算法

Python 递归回溯数独求解器

Java如何启动游戏回合类来存储回合数据

java - java中的for循环有什么问题

c# - 当一个对象从一个方法返回时,是创建了一个新的实例还是一个引用?

sql-server-2005 - SET NOCOUNT ON 真的能带来那么大的性能差异吗