树集的子集方法的复杂性?

时间:2015-03-16 00:24:23

标签: java time-complexity treeset

我正在寻找树集子集方法的时间复杂度。是O(n),其中n是导航集中的项目数?

2 个答案:

答案 0 :(得分:5)

TreeSet的subSet()方法在内部调用TreeMap的subMap()方法。 Java中的TreeMap是使用Red-Black树实现的。 subMap()方法返回SubMap类的新对象,该类是TreeMap中的一个内部类(嵌套类)。 SubMap类的构造函数仅存储subMap的第一个和最后一个键,如下所示:

SubMap(Object minKey, Object maxKey)
{
  if (minKey != nil && maxKey != nil && compare(minKey, maxKey) > 0)
    throw new IllegalArgumentException("fromKey > toKey");
  this.minKey = minKey;
  this.maxKey = maxKey;
}

除size()方法外,大多数操作与TreeMap花费相同的时间。 SubMap类的size()方法实现如下:

public int size()
{
  //Returns node >= minKey(i.e. first node in subSet). Takes O(logN) time.
  Node node = lowestGreaterThan(minKey, true);
  //Returns node >= maxKey(i.e. first node in subSet). Takes O(logN) time.
  Node max = lowestGreaterThan(maxKey, false);
  int count = 0;
  while (node != max)
    {
      count++;
      //In worst case, successor takes logN time
      node = successor(node);
    }
  return count;
}

最低的GreaterThan()方法采用O(logN)在子集中查找密钥。 successor()方法采用与红黑树中的高度成比例的O(logN)来查找下一个后继者。为了找到由subSet返回的NavigableSet的大小,我们需要遍历subSet中的每个节点。因此,函数SubMap.size()的总复杂度为:O(logN)+ O(logN)+ O(MlogN)〜O(MlogN),其中M为子集的大小。

答案 1 :(得分:-1)

参考:https://docs.oracle.com/javase/7/docs/api/java/util/TreeSet.html#subSet(E,%20boolean,%20E,%20boolean) 由于它返回子集的引用,我相信它需要 O(logn) 时间,n 是 treeSet 的大小。