Java:SortedSet“光标”式迭代器

发布于 2024-09-10 09:40:04 字数 386 浏览 0 评论 0原文

我需要在排序集中向前和向后迭代。如果我使用 NavigableSet,我得到一个严格前向迭代器和一个严格后向迭代器(iterator()descendingIterator()),但没有一个可以向前和向后移动。

NavigableSet.lower()higher() 的时间复杂度是多少?我可以使用它们,但如果它们效率低下,我就不愿意这样做。

I need to iterate both forwards and backwards in a sorted set. If I use NavigableSet, I get a strictly-forward iterator and a strictly-backward iterator (iterator() and descendingIterator()) but none that can move forward and backward.

What's the time complexity of NavigableSet.lower() and higher() ? I can use those instead, but am reluctant to do so if they are inefficient.

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

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

发布评论

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

评论(2

微暖i 2024-09-17 09:40:05

根据您的具体需求,您可以将排序集转换为列表(例如数组列表),并使用 列表迭代器用于遍历。它可以通过 next()previous() 方法,可以自由混合。

Depending on your exact needs you could convert the sorted set to a list, say an array list, and use a list iterator for traversal. It can be used in both directions via the next() and previous() methods, which may be mixed freely.

趁年轻赶紧闹 2024-09-17 09:40:05

NavigableSet 只有两种实现。假设您选择了 TreeSet,虽然我没有方便的源代码,但 Javadoc 说它基于 TreeMap 为 get/put/containsKey/remove 提供 O(log(n))。在最坏的情况下,这将执行一次 get 来查找我们正在查找的较低/较高值,再加上额外的搜索来获取下一个/上一个值,提供 O(2log(n)) = O(log(n)) 。

如果树实际上是一个列表,则搜索的最坏情况是 O(n),但一般来说,O(高度)。

There are only two implementations of the NavigableSet. Saying you opted for the TreeSet, while I don't have the source handy, the Javadoc says that it is based on a TreeMap providing O(log(n)) for get/put/containsKey/remove. At worst this would perform one get to find the value of we're finding the lower/higher for, plus an additional search to get the next/previous value, providing O(2log(n)) = O(log(n)).

Trees are worst case O(n) for search in the event it is actually a list, but in general, O(height).

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