18. 四数之和

254 阅读1分钟

题目描述

给定一个包含 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
-109 <= nums[i] <= 109
-109 <= target <= 109

来源:力扣(LeetCode)
链接:leetcode-cn.com/problems/4s…

分析

暴力求解的话需要4重循环,复杂度太高过不了。 这里将前2个数固定,后两个数使用左右指针。基本思路与三数之和类似
三数之和

实现

/**
 * 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 compare(const void *a, const void *b)
{
    return *(int*)a - *(int*)b;
}

int **fourSum(int *nums, int numsSize, int target, int *returnSize, int **returnColumnSizes)
{
    *returnSize = 0;
    if (numsSize < 4) {
        return NULL;
    }

    // result存放结果集, returnColumnSizes存放每1个结果的大小,这里固定4个(4数之和符合要求的结果肯定是4个)
    int **result = (int**)malloc(sizeof(int*) * 1000);
    *returnColumnSizes = (int*)malloc(sizeof(int) * 1000);

    // 先排序,让数组有序
    qsort(nums, numsSize, sizeof(nums[0]), compare);

    // 两层循环先把前两个数取出
    for (int i = 0; i < numsSize - 3; i++) {
        // 去重
        if (i > 0 && nums[i] == nums[i-1]) {
            continue;
        }
        for (int j = i + 1; j < numsSize - 2; j++) {
            // 去重
            if (j > i + 1 && nums[j] == nums[j-1]) {
                continue;
            }

            // 左右指针分别指向j+1(最小值)和numsSize-1(最大值),根据4数之和判断指针移动
            int left = j + 1;
            int right = numsSize - 1;
            while (left < right) {
                // 之所以要转换成long,是因为用例中包含4数和超过int范围的情况
                if ((long)nums[i] + nums[j] + nums[left] + nums[right] > target) {
                    right--;
                } else if ((long)nums[i] + nums[j] + nums[left] + nums[right] < target) {
                    left++;
                } else {
                    // 找到了1个组合,保存
                    int *preRes = (int*)malloc(sizeof(int) * 4);
                    preRes[0] = nums[i];
                    preRes[1] = nums[j];
                    preRes[2] = nums[left];
                    preRes[3] = nums[right];
                    (*returnColumnSizes)[*returnSize] = 4;
                    result[*returnSize] = preRes;
                    (*returnSize)++;
                    left++;
                    right--;

                    // 去重
                    while (left < right && nums[left] == nums[left-1]) {
                        left++;
                    }
                    while (left < right && nums[right] == nums[right+1]) {
                        right--;
                    }
                }
            }
        }
    }
    return result;
}