简体   繁体   English

Java特定的数据结构

[英]Java - specific data structure

I need to perform following operations : 我需要执行以下操作:

(1) check if elements exists in O(1) (1)检查O(1)中是否存在元素

(2) add in O(1) (2)加入O(1)

(3) remove and return in O(1) (3)删除并返回O(1)

I thought about Set in java , but it only supports (1) and (2). 我在Java中考虑过Set ,但它只支持(1)和(2)。 I know that it is possible to do something like this set.iterator().next() and set.iterator().remove() but what is the complexity of this solution ? 我知道可以做类似这样的事情set.iterator().next()set.iterator().remove()但是这个解决方案的复杂性是多少?

EDIT 编辑

I want something like this : 我想要这样的东西:

Set<Integer> remaining = new HashSet<>();

// add values

Queue<Integer> queue = new ArrayDeque<>();

while(!remaining.isEmpty()) {
    int val = remaining.iterator().next();   // !!!
    remaining.iterator().remove();          // !!!
    queue.add(val);

    while(!queue.isEmpty()) {

         List<Integer> valuesToBeRemoved = getValues();
         // some logic
         for(int value : valuesToBeRemoved) {
              remaining.remove(value);
         }

    }


}

and I am wondering if lines marked with // !!! 我想知道是否标有// !!! are optimal 是最佳的

HashSet has O(1) performance for add(E e) and contains(E e) . HashSet对于add(E e)具有O(1)性能并且contains(E e) To get any old element from a HashSet<Integer> (and remove it) you can write 要从HashSet<Integer>获取任何旧元素(并将其删除),您可以编写

Iterator<Integer> i = set.iterator();
int a = i.next();
i.remove();

When you do i.next() you might have to search empty hash buckets. 当你执行i.next()你可能需要搜索空的哈希桶。

If you use a LinkedHashSet rather than a HashSet , you get similar performance for add() and contains() , but i.next() is faster because a LinkedHashSet keeps a reference to the first element. 如果使用LinkedHashSet而不是HashSet ,则会获得类似add()contains() ,但i.next()更快,因为LinkedHashSet保留对第一个元素的引用。 In general it is much quicker to iterate over a LinkedHashSet than a HashSet because you just have to follow a chain of references. 通常,迭代LinkedHashSet要比HashSet快得多,因为你只需要遵循一系列引用。 Note however that a LinkedHashSet will be use more memory than a HashSet , but if it's speed you're interested in, LinkedHashSet is a good answer. 但请注意, LinkedHashSet将使用比HashSet更多的内存,但如果你感兴趣的话, LinkedHashSet是一个很好的答案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM