LeetCode 15 3个数之和 C语言 Python O(N^2)实现

给你一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?请你找出所有和为 0 且不重复的三元组。

注意:答案中不可以包含重复的三元组。

 

示例 1:

输入:nums = [-1,0,1,2,-1,-4]
输出:[[-1,-1,2],[-1,0,1]]
示例 2:

输入:nums = []
输出:[]
示例 3:

输入:nums = [0]
输出:[]

参考两个数之和的算法:三个数之和转换为固定其中一个数,求另外两个数之和,即a+b+c=0和a+b=-c是等价的。遍历并固定数组中的一个数,求其他元素中石油有两个数之和等于这个数的负数。

class Solution:
    def threeSum(self, nums: List[int]) -> List[List[int]]:
        length = int(len(nums))
        if(not nums or length < 3):
            return []
        res=[]
        nums.sort()        
        for first in range(length-2) :
            if nums[first] > 0 :
                return res
            if(first > 0 and nums[first]==nums[first-1]):
                continue
            left = first+1
            right = length-1       
            while left < right : 
                if nums[first]+nums[left]+nums[right] == 0 :
                    print(nums[first], nums[left], nums[right])
                    res.append([nums[first],nums[left],nums[right]])
                   
                    while(left < right and nums[left] == nums[left+1]): #为避免列表越界,两个条件顺序不能变
                        left+=1                                       
                    while(left < right and nums[right] == nums[right-1]):  #为避免列表越界,两个条件顺序不能变                     
                        right-=1 

                    left+=1 
                    right-=1  
                elif nums[first]+nums[left]+nums[right] < 0 : #为避免列表越界,使用elif 而不是if
                    left +=1
                else :
                    right -=1
        return res 

C 语言1

int CompareIncrease(void* a, void* b){
     return ( *(int *)a - *(int*)b);
 }
int** threeSum(int* nums, int numsSize, int* returnSize, int** returnColumnSizes){
    *returnSize = 0;
    if(0 == numsSize){
        return NULL;
    }

    int cur = 0; /*相当于目标值,寻找 left+right的和等于负cur*/
    int left = 0;
    int right = numsSize - 1;

    int** resultArray = (int**) malloc(sizeof(int*) * (numsSize)*(numsSize) );
    *returnColumnSizes = (int *) malloc(sizeof(int *) *(numsSize)*(numsSize));

    /*调用stdlib库快排*/
    qsort(nums, numsSize, sizeof(int), CompareIncrease);

    while(nums[cur] <= 0 && cur < numsSize - 2){
        left = cur + 1;
        right = numsSize - 1;
        while(left < right){
            if( (nums[cur] + nums[left] + nums[right]) == 0){
                resultArray[*returnSize] = (int*)malloc(sizeof(int) * 3);
                (*returnColumnSizes)[*returnSize] = 3; // 记录列数
                resultArray[*returnSize][0] = nums[cur];
                resultArray[*returnSize][1] = nums[left];
                resultArray[*returnSize][2] = nums[right];
                (*returnSize)++;

                // 往后去重(left)
                while( (nums[left] == nums[++left]) && (left < right) ); 
                // 往前去重(right)
                while( (nums[right] == nums[--right]) && (left < right) ); 
            }

            if((nums[cur] + nums[left] + nums[right]) < 0){
                left++;
            }
             if((nums[cur] + nums[left] + nums[right]) > 0){
                right--;
            }       
        }
        /*去重cur*/
        while( (nums[cur] == nums[++cur]) && (cur  < numsSize - 2) );
    }
    return resultArray;

}

C 语言2

/*按照升序进行快速排序*/
int compare(const void* a, const void* b) {
    return *(int *)a - *(int *)b;
}

int** threeSum(int* nums, int numsSize, int* returnSize, int** returnColumnSizes){
     int first =0, left = 0, right = 0, sum = 0;
    /* 先记录返回的行数为0, 即满足条件组合数为0*/
    *returnSize = 0;   
    /* 分配返回的二级指针, 即二维数组 */
    int** ret = (int**)malloc(numsSize * numsSize * sizeof(int*));
    /*分配返回数组的列数*/
     *returnColumnSizes = (int*)malloc(numsSize * numsSize *sizeof(int));
     /*排序*/
    qsort(nums, numsSize, sizeof(int), compare);
    
    for (first = 0; first < numsSize-2; first++){
        if(nums[first] > 0){
            return  ret;
        }
         /* 当前元素与上一次相等,跳过此次计算,去重 */
        if (first > 0 && nums[first] == nums[first - 1]) {
            continue;
        }
        left = first + 1;
        right = numsSize -1;
        while (left < right) { 
            sum = nums[first] + nums[left] + nums[right];
            if (sum == 0){
                ret[*returnSize] = (int*)malloc(sizeof(int) * 3);/*为满足条件的其中一种组合分配存储地址*/
                ret[*returnSize] [0]= nums[first]; 
                ret[*returnSize] [1]= nums[left]; 
                ret[*returnSize] [2]= nums[right]; 
                 /* 本次满足条件的数组的列数为3 */
                (*returnColumnSizes)[*returnSize] = 3;
                /* 返回数组的行数自加1 */
                (*returnSize)++;
                /*排除与前一个元素相等的情况*/
                while (left < right && nums[left]  == nums[++left]);
                while (left < right && nums[right]  == nums[--right]);
            } else if (sum < 0){
                left++;
            }else {
                right--;
            }
        }

    }
    return ret;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值