什么是O(1)的数据结构,用于在任何位置追加,预处理和检索元素?

编程入门 行业动态 更新时间:2024-10-16 00:19:08
本文介绍了什么是O(1)的数据结构,用于在任何位置追加,预处理和检索元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在寻找Java解决方案,但是任何一般的答案也是可以的。

Vector / ArrayList是用于追加和检索的O(1),但是O )用于前缀。

LinkedList(在Java中实现为双向链表)是O(1),用于追加和前缀,但O(n)用于检索。 / p>

Deque(ArrayDeque)对于上面的所有内容都是O(1),但不能在任意索引处检索元素。

在我看来,满足上述要求的数据结构有2个可扩展列表(一个用于前置,一个用于追加),并且还存储偏移量以确定在哪里获取

解决方案

您正在寻找一个双端队列。这是按照您想要的方式在C ++ STL中实现的,您可以将其索引到其中,但不能在Java中进行索引。您可以通过使用两个数组来存储标准组件,并将其存储在零位置。如果你最终从零开始很长一段时间,这可能会浪费记忆力,但是如果你太过分了,你可以修改并允许deque爬行到一个新的数组。

一个更优雅的解决方案在管理两个数组中并不需要太多的幻想,就是将一个循环数组强加到一个预先分配的数组上。这将需要在其后面实现push_front,push_back和调整数组的大小,但是调整大小的条件等等会更加清晰。

I'm looking for Java solution but any general answer is also OK.

Vector/ArrayList is O(1) for append and retrieve, but O(n) for prepend.

LinkedList (in Java implemented as doubly-linked-list) is O(1) for append and prepend, but O(n) for retrieval.

Deque (ArrayDeque) is O(1) for everything above but cannot retrieve element at arbitrary index.

In my mind a data structure that satisfy the requirement above has 2 growable list inside (one for prepend and one for append) and also stores an offset to determine where to get the element during retrieval.

解决方案

You're looking for a double-ended queue. This is implemented the way you want in the C++ STL, which is you can index into it, but not in Java, as you noted. You could conceivably roll your own from standard components by using two arrays and storing where "zero" is. This could be wasteful of memory if you end up moving a long way from zero, but if you get too far you can rebase and allow the deque to crawl into a new array.

A more elegant solution that doesn't really require so much fanciness in managing two arrays is to impose a circular array onto a pre-allocated array. This would require implementing push_front, push_back, and the resizing of the array behind it, but the conditions for resizing and such would be much cleaner.

更多推荐

什么是O(1)的数据结构,用于在任何位置追加,预处理和检索元素?

本文发布于:2023-11-30 02:07:19,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1648368.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数据结构   元素   位置

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!