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];
                [sub addObject:num];
                [sub addObject:nums[left]];
                [sub addObject:nums[right]];
                [list addObject:sub];
                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;
}

推荐阅读更多精彩内容