集合 03 集合的时间复杂度分析

LinkedListSet 和 BSTSet 的时间复杂度对比

  • LinkedListSet 的效率明显比 BSTSet 的慢;
  • 原因是:LinkedListSet 在 add 的时候需要先判断一下链表中是否存在待添加元素,而 contains 的时间复杂度是 O(n),所以 LinkedListSet 的 add 的时间复杂度是 O(n);而 BSTSet 的 add 的时间复杂度是 O(logn) 的,所以 LinkedListSet 的效率比 BSTSet 的明显慢;
public class Main {

    private static double testSet(Set set, String filename){
        long startTime = System.nanoTime();

        System.out.println(filename);
        ArrayList words = new ArrayList<>();
        if(FileOperation.readFile(filename, words)) {
            System.out.println("Total words: " + words.size());

            for (String word : words)
                set.add(word);
            System.out.println("Total different words: " + set.getSize());
        }

        long endTime = System.nanoTime();
        return (endTime - startTime) / 1000000000.0;
    }

    public static void main(String[] args) {
        String filename = "pride-and-prejudice.txt";

        BSTSet bstSet = new BSTSet<>();
        double time1 = testSet(bstSet, filename);
        System.out.println("BST Set: " + time1 + " s");

        System.out.println();

        LinkedListSet linkedListSet = new LinkedListSet<>();
        double time2 = testSet(linkedListSet, filename);
        System.out.println("Linked List Set: " + time2 + " s");

    }

}
输出
a-tale-of-two-cities.txt
Total words: 141489
Total different words: 9944
BST Set: 0.193731401 s

a-tale-of-two-cities.txt
Total words: 141489
Total different words: 9944
Linked List Set: 5.102809299 s

BSTSet的时间复杂度

  • add:O(h) = O(log2(n+1)) = O(logn)
  • contains:O(h) = O(log2(n+1)) = O(logn)
  • remove:O(h) = O(log2(n+1)) = O(logn)
  • 注意:h = log2(n+1) 是以满二叉树的情况下计算出的,二叉树在极端的情况下可以退化成链表,此时 h = n,当以1,2,3,4,5,6 这样的顺序向 BST 中添加元素的时候就可以让 BST 退化成链表,解决这个问题的方案就是创建平衡二叉树;

LinkedListSet的时间复杂度

  • add:O(n)
  • contains:O(n)
  • remove:O(n)

特别注意

  • 基于链表实现的集合是无序集合;
  • 基于 BST 实现的集合是有序集合;

你可能感兴趣的:(集合 03 集合的时间复杂度分析)