字典实现(平衡二叉搜索树与哈希表)

发布于 2024-11-01 02:32:15 字数 167 浏览 1 评论 0原文

在什么情况下使用平衡二叉搜索树而不是哈希表来实现字典ADT会更好?

我的假设是使用二叉搜索树总是更好,因为它的自然排序。

但哈希表的搜索时间确实可以与 O(1) 一样好,而二叉树的搜索时间则为 O(logn) 。

所以我不确定情况会怎样。

Under what circumstances would it be better to implement a Dictionary ADT using a balanced binary search tree rather than a hash table?

My assumption was that it is always better to use a binary search tree because of its natural ordering.

But it's true that the hash table's search time can be as good as O(1) , v.s. O(logn) for the binary tree.

so I'm not sure what the circumtaces would be.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

删除→记忆 2024-11-08 02:32:15

当哈希表被填满并且需要重新分配内存时(在硬实时系统的上下文中),哈希表可能会出现性能问题。二叉树不存在这个问题。
哈希表需要比实际使用更多的内存,而二叉树则使用所需的内存。

Hash tables might have a performance issue when they get filled up and need to reallocate memory (in the context of a hard real-time system).Binary trees don't have this issue.
Hash tables need more memory than they actually use, where as binary trees use as much memory as they need.

五里雾 2024-11-08 02:32:15

您的问题已经包含答案:

如果您不需要任何内在排序,则使用哈希表以获得更好的性能。如果您的要求需要某种排序,那么请考虑使用树。

Your question already contains the answer:

If you don't require any intrinsic ordering then use a hashtable for better performance. If your requirements demand some kind of ordering then consider using a tree.

纵情客 2024-11-08 02:32:15

Dictionary 的时间复杂度是:

-----------------------------------------
| Operation   |  Dictionary |    BST    | 
-----------------------------------------
| Insert      |  O(1)       | O(log(n)) |
-----------------------------------------
| Delete      |  O(1)       | O(log(n)) |
-----------------------------------------
| Search      |  O(1)       | O(log(n)) |
-----------------------------------------

那么你在哪里使用 BST 和 Dictionary 呢?以下是 BST 的一些主要优点。

  • 使用 BST,您总是需要 O(log(n)) 操作,但调整哈希表大小是一项成本高昂的操作。
  • 如果您需要按排序顺序获取键,您可以让它们遍历中序树。排序对于字典来说并不自然
  • 进行统计,例如查找最接近的较低和较大元素,或范围查询。

The time complexity for Dictionary is:

-----------------------------------------
| Operation   |  Dictionary |    BST    | 
-----------------------------------------
| Insert      |  O(1)       | O(log(n)) |
-----------------------------------------
| Delete      |  O(1)       | O(log(n)) |
-----------------------------------------
| Search      |  O(1)       | O(log(n)) |
-----------------------------------------

So where do you use BST vs Dictionary? Here are some main advantages of BST.

  • With BST you always have O(log(n)) operation, but resizing a hash table is a costly operation
  • If you need to get keys in a sorted order you can get them traversing inorder tree. Sorting is not natural to a dictionary
  • Doing statistics, like finding the closest lower and greater element, or range query.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文