问题
I have to make a data structure with certain conditions.
First these 4 functions must be in O(log(n)):
insert(Object o)
insert(int index, Object o)
delete(int index)
update(int index, Object o)
Second: The data structure must implement java.util.List
My issue is with the O(log(n)) and the List. There are a lot of trees that can do the operation in O(log(n)) (like BST, Red-Black Tree, AVL Tree), but how can these trees be indexed and how can the insert be anywhere?
Setting this up as only a list does bring up issues.
java.util.List
has these implementing classes:
AbstractList
, AbstractSequentialList
, ArrayList
, LinkedList
, Stack
, Vector
Most of these classes have methods of O(1) and O(1) < O(log(n)), but there is always a method that is O(n). Example the ArrayList has a remove of O(n).
Does anyone have any advise or approaches to this problem?
Basically, I am looking for a data structure that I'll fulfill those requirements.
回答1:
An indexable skip list seems to fit the bill: inserts and deletes are O(log n), and index access for update
is also O(log n).
回答2:
My issue is with the O(log(n)) and the List. There are a lot of trees that can do the operation in O(log(n)) (like BST, Red-Black Tree, AVL Tree), but how can these trees be indexed and how can the insert be anywhere?
If you just include a subtreeSize
field in your Node
class, and keep it up-to-date as you insert/delete/rotate/etc. (which involves some bookkeeping, but won't affect your asymptotic complexities), then you can infer the index of any given node by the size of its left-child's subtree and those of its ancestors.
Your result will be a bit different from those, though, in that those trees are all sorted, whereas you just want to preserve the order specified by the insert operations. So while you should definitely have those in the back of your mind as you think about keeping your tree balanced, don't let yourself be led astray by irrelevant aspects.
回答3:
You could try making a Hashmap using the List. That way your insert, delete, and search are all O(1)
. A simple approach could be making a list that contains linked lists and then coming up with a good hash function to minimize collisions. Then all you have to do is actually coding these functions and you will hopefully have the performance requirements you need (just use efficient algorithms).
来源:https://stackoverflow.com/questions/42560005/list-as-ologn