如果我将 HashSet 转换为 TreeSet,时间复杂度是多少。

huangapple go评论65阅读模式
英文:

What is the time complexity if i converted HashSet to TreeSet

问题

如果我想使用构造函数创建一个新的TreeSet,在这种情况下时间复杂度会是多少呢?

HashSet<Integer> hashSet = new HashSet<>();

for (int i = 0; i < arr.length; i++){
    hashSet.add(arr[i]);
}

TreeSet<Integer> treeSet = new TreeSet<>(hashSet);
英文:

If i want to create a new TreeSet by using the constuctor what would be the time complexity in this case?

HashSet&lt;Integer&gt; hashSet = new HashSet&lt;&gt;();

for (int i = 0; i &lt; arr.length; i++){

    hashSet.add(arr[i]);

}

TreeSet&lt;Integer&gt; treeSet = new TreeSet&lt;&gt;(hashSet);

答案1

得分: 1

TreeSet(Collection) 构造函数只是逐个添加每个元素 - 而对于 TreeSet,添加每个元素通常需要 O(log n) 的时间。因此,整个操作需要 O(n log n) 的时间。

英文:

The TreeSet(Collection) constructor simply adds each element one at a time -- and adding each element, as usual for a TreeSet, takes O(log n). Therefore, the whole operation takes O(n log n).

huangapple
  • 本文由 发表于 2020年10月15日 00:42:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/64357911.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定