我有两个数组如下
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};
我怎样才能做到这一点。请有任何建议。
我有两个数组如下
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};
我怎样才能做到这一点。请有任何建议。
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);
NSMutableSet * wants = [NSMutableSet setWithArray:firstArray];
NSMutableSet * union = [[NSMutableSet setWithArray:secondArray] unionSet:wants];
NSMutableArray *array = [NSMutableArray arrayWithArray:[union allObjects]];