简体   繁体   中英

Java - specific data structure

I need to perform following operations :

(1) check if elements exists in O(1)

(2) add in O(1)

(3) remove and return in O(1)

I thought about Set in java , but it only supports (1) and (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 ?

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) . To get any old element from a HashSet<Integer> (and remove it) you can write

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

When you do i.next() you might have to search empty hash buckets.

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. In general it is much quicker to iterate over a LinkedHashSet than a HashSet because you just have to follow a chain of references. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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