LeetCode:15. 3Sum 三数之和(C语言)

题目描述:
给定一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?找出所有满足条件且不重复的三元组。

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

示例:

给定数组 nums = [-1, 0, 1, 2, -1, -4],

满足要求的三元组集合为:
[
[-1, 0, 1],
[-1, -1, 2]
]

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/3sum
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解答:

/**
 * 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().
 */

 #define LEN 0xffff

int comp (const void *a , const void *b)
{
    return *(int *)a - *(int *)b;
}

int** threeSum(int* nums, int numsSize, int* returnSize, int** returnColumnSizes)
{
	
	//为二位数组申请内存空间
	int** ret = (int**)malloc(sizeof(int*) * LEN);
	memset(ret, 0, sizeof(int*) * LEN);
	
	//每个字符串长度
	int* rcs = (int *)malloc(sizeof(int) * LEN);
	memset(rcs, 0, sizeof(int) * LEN);
	
    //排序
	qsort(nums, numsSize, sizeof(nums[0]), comp);
    
	//字符串的个数
	int retIndex = 0;
	
	int i = 0;

	for (i = 0; i < numsSize; i++) 
    {
		
		//若排序后最小值大于0,则后两个大于0
		if (nums[i] > 0) 
        {
			break;
		}
		
		//去重
		if (i > 0 && nums[i] == nums[i - 1]) 
        {
			continue;
		}
		
		int left = i + 1;
		int right = numsSize - 1;
		
		while (left < right) 
        {
			int sum = nums[i] + nums[left] + nums[right];

			if (sum == 0) 
            {
                ret[retIndex] = (int*)malloc(sizeof(int) * 3);
                memset(ret[retIndex], 0, sizeof(int) * 3);

				ret[retIndex][0] = nums[i];
				ret[retIndex][1] = nums[left];
				ret[retIndex][2] = nums[right];
				retIndex++;
				
				while (left < right && nums[left] == nums[left + 1]) 
                {
					left++;
				}
				while (left < right  && nums[right] == nums[right - 1]) 
                {
					right--;
				}

				left++;
				right--;
			} 
            else if (sum < 0) 
            {
				left++;
			} 
            else if (sum > 0) 
            {
				right--;
			}	
		}
	}
	
	for (i = 0; i < retIndex; i++) 
    {
		rcs[i] = 3;
	}
	
	*returnColumnSizes = rcs;   //列数
	*returnSize = retIndex;	    //行数

    return ret;
}

运行结果:
LeetCode:15. 3Sum 三数之和(C语言)_第1张图片

你可能感兴趣的:(LeetCode)