給定一個(gè)數(shù)組和目標(biāo)值凡泣,求數(shù)組的兩個(gè)數(shù)之和等于目標(biāo)值,并返回兩數(shù)在數(shù)組中的下標(biāo)值
- (void)test {
NSMutableArray *mutArr = [self sumOfTwoNumber:@[@2, @7, @11, @15, @2, @7] target:9];
NSLog(@"%@", mutArr);
}
- (NSMutableArray *)sumOfTwoNumber:(NSArray *)array target:(NSInteger)target {
NSMutableArray *mutArr = [NSMutableArray array];
for (NSInteger i = 0; i < array.count - 1; i++) {
for (NSInteger j = i + 1; j < array.count; j++) {
if ([array[i] integerValue] + [array[j] integerValue] == target) {
[mutArr addObject:[NSString stringWithFormat:@"{%ld,%ld}", i, j]];
}
}
}
return mutArr;
}
打印出來(lái)的結(jié)果為:
(
"{0,1}",
"{0,5}",
"{1,4}",
"{4,5}"
)