# 15. 三数之和

``````+ (NSArray*)threeSum:(NSArray *)nums {

if (nums == nil) return nil;

NSMutableArray *list = [NSMutableArray array];

if (nums.count < 3) return list;

nums = [nums sortedArrayUsingComparator:^NSComparisonResult(NSNumber *  _Nonnull obj1, NSNumber*  _Nonnull obj2) {
return obj1.intValue - obj2.intValue;
}];

for (NSInteger i = 0; i < nums.count - 3; i++) {

if (i > 0 && [nums[i] isEqualToNumber:nums[i-1]]) continue;

NSNumber *num = nums[i];
NSInteger left = i + 1, right = nums.count - 1, remin = -(num.intValue);

while (left < right) {

NSNumber *leftVal = nums[left], *rightVal = nums[right];

NSInteger leftValue = leftVal.integerValue, rightvalue = rightVal.integerValue, totalValue = leftValue + rightvalue;

if (totalValue == remin) {

NSMutableArray *sub = [NSMutableArray array];
while (left < right && [nums[left] isEqualToNumber:nums[left+1]]) left++;
while (left < right && [nums[right] isEqualToNumber:nums[right-1]]) right--;
left++;
right--;

} else if (totalValue < remin) {
left++;
} else {
right--;
}
}
}

return list;
}
``````