The fastest way to do a subtraction collection

I have two sets. Set b- a subset Set a. They are both very large Sets. I want to subtract b from what is best done for this general operation? I have written a lot of codes like this and I do not find it effective. what is your idea

pseudo code: (this is not a Java API).

for(int i = 0 ; i < a.size(); i++) {
          for (int j=0 ; j < b.size() ;j++) {
              // do comparison , if found equals ,remove from a
              break;
          }
 }

And I want to find an algorithm that not only applies to Sets, but also works for Array.

EDIT: the set here is not a JAVA API, it is a data structure. so I don’t care if the Java API has a removeAll () method, I want to find a common solution for this problem, I am faced with a lot of problems like this when I use Javascript and Actionscript.

+5
8

, , a.removeAll(b);. removeAll() Java-API.

: - O (n ^ 2), , ( - , ). , . removeAll() . , Hash, , , . , , , - , HashSet.: -)

: , , Java. removeAll() - Java-API, ( - ) . , - , for-loops . , . ( ), ( O (n)):

int bIndex = 0;
for(int i = 0 ; i < a.size(); i++) {
          while (a[i] < b[bIndex]) {bIndex++;}
          if (a[i] == b[bIndex]) {markForRemoval(a[i]);} // I mark this only for removal, as the actual removal would make your index incorrect
}

, , b. .

+8

, , , , .

-, - , , , , B A , , .

, Java-, , removeAll(), , - . HashSet.

+1

, , O (n). , , , — ( ) .

"removeAll", , , O (n).

( , &mdash, .. , , O (n log n), .)

+1

, : . O(1), O(min(m,n)) , , , (, /).

actionscript 3, Dictionary. .

:

for each (var key:* in set2) {//a simple for-in loop will also do the trick, since keys and values are equal, but for-each-in loops perform faster
    delete set1[key];
}

JavaScript, , . .

:

for (var key in set2) {
    delete set1[key];
}
+1

, b a, , 2 . :

foreach b in B
    remove b from A

, , , , , .

+1

removeAll Set?

.

0

, java.util.HashSet.removeAll(Collection toRemove), . , , , .

0

, , O (N ^ 2), , .

// A is some kind of array, O(1) iteration
// B is a hash containing elements to remove, O(1) contains(elt)
List<T> removeAll(List<T> A, Set<T> B) {
  List<T> result; // empty, could preallocate at |A|
  for (elt : A) { // for each 'elt' belonging to A, hence O(|A|)
    if (! B.contains(elt) ) { // O(1) thanks to hash
      C.add(elt) ; // ensure this is O(1) with preallocation or linked list
    }
  }
  return result;
}

B, -. Java Set<T> Bh = new HashSet<T>(B);, O (| B |) . , O (| A | + | B |) O (2 | A | +2 | B |)) . , removeAll, (TM).

, ( ), A , ( ).

0

All Articles