给定一个数组和目标值,求数组的两个数之和等于目标值,并返回两数在数组中的下标值
- (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;
}
打印出来的结果为:
(
"{0,1}",
"{0,5}",
"{1,4}",
"{4,5}"
)