-5

我有两个数组如下

  firstArray={1,2,3,5,6,8,9,10,11} ;
  secondArray={1,2,3,4,7,8,10} ;

从这两个数组中,我需要得到结果数组:

  resultant ={1,2,3,4,5,6,7,8,9,10,11};

我怎样才能做到这一点。请有任何建议。

4

2 回答 2

4

There are so many ways to do :

You need to sort the array once two are merged, so as to produce the desired result

Starting with the basic way :

NSArray *firstArray=@[@1,@2,@3,@5,@6,@8,@9,@10,@11];
NSArray *secondArray=@[@1,@2,@3,@4,@7,@8,@10];

NSMutableArray *merged=[NSMutableArray arrayWithArray:firstArray];
for (id element in secondArray) {
    if (![merged containsObject:element]) {
        [merged addObject:element];
    }
}

NSLog(@"Merged %@",merged);

Using Set

NSSet *firstSet=[NSSet setWithArray:firstArray];
NSSet *secondSet=[NSSet setWithArray:secondArray];

NSMutableSet *unionFirstSecondSet=[NSMutableSet new];
[unionFirstSecondSet unionSet:firstSet];
[unionFirstSecondSet unionSet:secondSet];

NSLog(@"Merged %@",unionFirstSecondSet);

Using Dictionary

NSMutableDictionary *mergeDict=[NSMutableDictionary dictionaryWithObjects:firstArray forKeys:firstArray];
for (id element in secondArray) {
    [mergeDict setObject:element forKey:element];
}
NSArray *mergedArray=[mergeDict allKeys];

NSLog(@"Merged %@",mergedArray);

Using some array API tweaks

NSMutableArray *mergedArray=[[NSMutableArray alloc]initWithArray:firstArray];
[mergedArray addObjectsFromArray:secondArray];
for (id object in secondArray) {
    [mergedArray removeObjectIdenticalTo:object];
}
[mergedArray addObjectsFromArray:secondArray];

NSLog(@"Merged %@",mergedArray);
于 2013-01-18T13:14:01.277 回答
0
NSMutableSet * wants = [NSMutableSet setWithArray:firstArray];
NSMutableSet * union = [[NSMutableSet setWithArray:secondArray] unionSet:wants];

NSMutableArray *array = [NSMutableArray arrayWithArray:[union allObjects]];
于 2013-01-18T12:47:03.073 回答