java - 计算链表交集的空间复杂度是多少

标签 java algorithm space-complexity

我正在计算 2 个链表的交集,其中一个链表的大小为“n”,第二个链表的大小为“m”。下面的代码将较小链表的项目存储在一个集合中。因此空间复杂度为 O(m),其中 m < n,又名,m 是较小链表的长度。

但是,有可能 2 个链表是相等的,m = n。那么复杂度是 O(n) 吗?

public IntersectionAndUnionLinkedList<T> intersection(IntersectionAndUnionLinkedList<T> list) {
        final Set<T> items = new HashSet<>();

        Node<T> firstSmall = null;
        Node<T> firstBig   = null;

        if (size <= list.size) {
            firstSmall = first;
            firstBig = list.first;
        } else {
            firstSmall = list.first;
            firstBig = first; 
        }


        Node<T> n = null;
        for (n = firstSmall; n != null; n = n.next) {
                items.add(n.item);
        }

        IntersectionAndUnionLinkedList<T> intersectionlist = new IntersectionAndUnionLinkedList<>();
        for (n = firstBig; n != null; n = n.next) {
            if (items.contains(n.item)) {
                intersectionlist.add(n.item);
            }
        }

        return intersectionlist;
    }

最佳答案

万一 m=nO(m)=O(n),但可以肯定地说内存复杂度是 O( m) 因为它是唯一真实的因素。

另一方面,HashSet<T>在极端情况下可能会降低内存效率:毕竟它使用了桶,桶可能会以糟糕的方式填充。这取决于 HashMap<T> 的确切实现.尽管人们仍然期望线性内存复杂度为 O(m)

关于java - 计算链表交集的空间复杂度是多少,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27610776/

相关文章:

java - 转换为父类(super class)类型 a "Class"

algorithm - 如何在 O(n) 时间内对单链表进行二分查找?

java - 使用 Mongo Java 驱动程序从 MongoDB 数据库中提取数据

java - "java.text.ParseException: Unparseable date: "2017 年 6 月 18 日,5 :39AM"

java - Android Studio : Buttons not showing up during editing mode in RelativeLayout

c++ - 我的快速选择算法没有返回正确的值

c++ - 给定一组字符和长度的排列

java - 如何找到这段代码的时间和空间复杂度?

java - Java中Arraylist的交集性能(时间和空间)

algorithm - 为什么下面的代码只有空间复杂度O(N)?