如何使用预先排序的数据初始化 TreeMap?
我的应用程序使用 TreeMap 来保持数据排序并进行 log(n) 查找和插入。这在应用程序运行时的一般情况下效果很好,但是当应用程序首次启动时,我需要使用按排序顺序(升序)获得的数百万个长整型来初始化 TreeMap。
由于这些初始化值已经排序,有什么方法可以将它们插入到TreeMap中,而无需支付树插入和重新平衡的log(n)成本?
My app uses a TreeMap to keep data sorted and have log(n) lookups & inserts. This works great in the general case while the app is running, but when the app first starts, I need to initialize the TreeMap with several million longs that I get in sorted order (ascending).
Since these initialization values are already sorted, is there any way to insert them into the TreeMap without paying the log(n) cost of tree insertion and re-balancing?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当然!
TreeMap.putAll
方法(以及采用 SortedMap 的 TreeMap 构造函数)调用名为buildFromSorted
内部,在文档中描述为:“线性时间来自排序数据的树构建算法”,所以这听起来像是你想要的。只需为
putAll
方法提供一些实现 Map 的方法,但地图的条目集迭代器 (Map.entrySet().iterator()
) 返回已排序值的列表。Sure! The
TreeMap.putAll
method (and the TreeMap constructor that takes a SortedMap) calls a method calledbuildFromSorted
internally, which is described in the docs as: "Linear time tree building algorithm from sorted data", so that sounds like it does what you want.Just give the
putAll
method something that implements Map, but where the map's entryset iterator (Map.entrySet().iterator()
) returns your list of sorted values.