《LeetCode之每日一题》:13. 四数之和(C)

该篇博客详细解析了一道编程题目,涉及寻找数组中四个元素的组合使其和等于目标值。通过排序和双指针技巧,实现了O(N^3)的时间复杂度解决方案,适用于数组长度小于200且元素范围在负数亿到正数亿的情况。博客讨论了算法思路、代码实现及优化细节。
摘要由CSDN通过智能技术生成

四数之和


题目链接: 四数之和

有关题目

给定一个包含 n 个整数的数组 nums 和一个目标值 target,判断 nums 中是否存在
四个元素 a,b,c 和 d ,使得 a + b + c + d 的值与 target 相等?
找出所有满足条件且不重复的四元组。
示例 1:

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

输入:nums = [], target = 0
输出:[]
提示:

0 <= nums.length <= 200
-10^9 <= nums[i] <= 10^9
-10^9 <= target <= 10^9

题解

三数之和相类似

/**
 * Return an array of arrays of size *returnSize.
 * The sizes of the arrays are returned as *returnColumnSizes array.
 * Note: Both returned array and *columnSizes array must be malloced, assume caller calls free().
 */
 int cmp_int (const void* e1, const void* e2)
{
	return *(int*)e1 - *(int*)e2;
}
int** fourSum(int* nums, int numsSize, int target, int* returnSize, int** returnColumnSizes){
    *returnSize = 0;
	if(nums == NULL || numsSize < 4)
		return NULL;
	int first = 0,second = 0;
	/* 将nums排序为升序排列 */
	qsort(nums,numsSize,sizeof(int),cmp_int);
	/* 分配返回数组、返回数组的列数 */
	int** ret = (int**)malloc( sizeof(int*) * numsSize * numsSize);
	*returnColumnSizes = (int*)malloc(numsSize * numsSize * sizeof(int));//返回数组的行数
	for (first = 0; first < numsSize - 3; first++)
	{
		//保证和上一次枚举的数字不一样
		if (first > 0 && nums[first - 1] == nums[first] )
				continue;
		int second = first + 1;
        for (;second < numsSize - 2; second++)
        {
            int third = second + 1;
            int fourth = numsSize - 1;
            //保证和上一次枚举的数字不一样
            if (second > first + 1 && nums[second] == nums[second - 1])
                continue;
            while(third < fourth)
		{
			int sum = nums[first] + nums[second] + nums[third] + nums[fourth];
			if ( sum == target )
			{
				ret[*returnSize] = (int*)malloc(sizeof(int) * 4);
				ret[*returnSize][0] = nums[first];
				ret[*returnSize][1] = nums[second];
				ret[*returnSize][2] = nums[third];
                ret[*returnSize][3] = nums[fourth];
				/* 返回数组当前行的列数为4 */
                (*returnColumnSizes)[*returnSize] = 4;
				//行数加1
				(*returnSize)++;
				//对指向c,d的指针进行去重操作
				while(third < fourth && nums[third] == nums[++third]);
				while(third < fourth && nums[fourth] == nums[--fourth]);
			}
			else if (sum < target)
				third++;
			else
				fourth--;
		}	
        }
		
	}
        return ret;

}

时间复杂度:O(N^3)
空间复杂度:O(N)
在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值