TreeSet迭代的时间复杂度是多少?

发布于 2024-08-31 07:12:30 字数 217 浏览 2 评论 0原文

在我的代码中,Java TreeSet 迭代是占主导地位的时间因素。在观察这个系统时,我相信它的复杂度是 O(n) 。任何人都可以验证这一点吗?

我认为通过提供从子节点到父节点的向后链接我可以提高性能。

In my code, Java TreeSet iteration is the dominant time factor. In looking at the system I believe that it is O(n) complexity. Can anyone verify this?

I am thinking that by providing links backward from child node to parent node I could improve the performance.

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

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

发布评论

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

评论(2

鹿港巷口少年归 2024-09-07 07:12:30

TreeSet 迭代当然是 O(n),正如任何合理的树遍历算法所期望的那样。

我认为通过提供链接
从子节点向后到父节点
节点我可以提高性能。

TreeMapTreeSet 所基于的)已经有这样的父引用。这就是方法:

private Entry<K,V> successor(Entry<K,V> t) {
    if (t == null)
        return null;
    else if (t.right != null) {
        Entry<K,V> p = t.right;
        while (p.left != null)
            p = p.left;
        return p;
    } else {
        Entry<K,V> p = t.parent;
        Entry<K,V> ch = t;
        while (p != null && ch == p.right) {
            ch = p;
            p = p.parent;
        }
        return p;
    }
}

TreeSet iteration is of course O(n), as can be expect from any sensible tree-walking algorithm.

I am thinking that by providing links
backward from child node to parent
node I could improve the performance.

TreeMap (which TreeSet is based on) already has such parent references. This is the method it all boils down to:

private Entry<K,V> successor(Entry<K,V> t) {
    if (t == null)
        return null;
    else if (t.right != null) {
        Entry<K,V> p = t.right;
        while (p.left != null)
            p = p.left;
        return p;
    } else {
        Entry<K,V> p = t.parent;
        Entry<K,V> ch = t;
        while (p != null && ch == p.right) {
            ch = p;
            p = p.parent;
        }
        return p;
    }
}
记忆消瘦 2024-09-07 07:12:30

您是否考虑过在更改 TreeSet 时获取其副本?如果主要时间花在 TreeSet 迭代(而不是修改它)上,那么将 TreeSet 复制到数组或 ArrayList(仅在更改时)并且仅迭代此数组/ArrayList 几乎可以消除 TreeSet 迭代的成本。

Have you considered taking a copy of the TreeSet when you alter it? If the dominate time is spent in TreeSet iteration (rather than modifying it) then copying the TreeSet to an array or ArrayList (only when altered) and only iterating over this array/ArrayList could almost elminate the cost of TreeSet iteration.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文