Giffary
Giffary

Reputation: 3128

Union, intersect, difference large IntSet in O(m+n) times

From my question

Insert element to ArrayList with ascending order and no duplicate elements

I've done my insert method.

Now I try to find out how to build union, intersection, and difference methods to operate on 2 IntSets.

Notice that the number elements of IntSet is large and I need to do it in O(m+n) time where m and n are the number of elements of the two IntSets.

For example IntSets

a = new IntSetExtra();
b = new IntSetExtra();

for(int i=0; i<300; i++){ a.insert(2*i); }
for(int i=0; i<300; i++){ a.insert(i); }

for(int i=20000; i<50000; i++){ b.insert(i); }

How can I do it?

P.S. it can use mergesort?

edit:

Here is my union code

public IntSetExtra union(IntSetExtra a){
    //effect: return new IntSet that union between this and a;
    IntSetExtra intSet = new IntSetExtra();
    intSet.addAll(a);
    for(int i=0; i<a.size(); i++){
        if(!intSet.contains(a.get(i))){
            intSet.insert(a.get(i));
        }
    }
    return intSet;
}

Upvotes: 1

Views: 830

Answers (1)

Kru
Kru

Reputation: 4235

You may just use the methods of java collections such as addAll(Collection), removeAll(Collection) and retainAll(Collection).

For example, the intersection of two sets:

public Set<V> intersection(Set<? extends V> a, Set<? extends V> b) {
  // you may swap a and b, so a would contain the smaller collection
  Set<V> result = new HashSet<V>(a);
  result.retainAll(b);
  return result;
}

Upvotes: 2

Related Questions