Is your NSArray you want to delete already sorted? This is similar to your question. In this case, the following code will be executed:
NSMutableArray *uniqueItems = [NSMutableArray array]; id lastSeenUniqueObject = nil; for (NSObject *item in allItems) { if (![item isEqual:lastSeenUniqueObject]) { [uniqueItems addObject:item]; lastSeenUniqueObject = item; } }
It has a N (i.e. fast) runtime complexity, compared to (approximate) N ^ 2 rpetrich answer complexity.
If you do not know that the contents of the array are sorted, you have two options:
A) just sort it and then apply the above algorithm, which gives n log n complexity of execution (even better than N ^ 2),
or
B) Use an NSMutableSet to track objects already seen (or any other data structure using buckets and hashing). The code will look like this:
NSMutableArray *uniqueItems = [NSMutableArray array]; NSMutableSet *seenItems = [NSMutableSet set]; for (NSObject *item in allItems) { if (![seenItems containsObject:item]) { [uniqueItems addObject:item]; [seenItems addOBject:item]; } }
It also gives runtime better than N ^ 2.
occulus
source share