第十八题:四数之和

题目描述

给定一个包含 n 个整数的数组 nums 和一个目标值 target,找出 nums 中的四个整数,使得它们的和等于 target。你可以假设每个输入都只有一个解决方案,并且不能使用同一个元素多次。

实现思路

采用排序加双指针的方法来解决这个问题。首先对数组进行排序,然后遍历数组,对于每一个元素,设定一个新的目标值为原目标值减去这个元素的值,再利用三数之和的解法找到剩下的三个数。为了避免重复,在遍历过程中需要跳过与前一元素相同的元素。

算法实现

C

c 复制代码
#include <stdio.h>
#include <stdlib.h>

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

void fourSumUtil(int *nums, int numsSize, int start, int end, int target, int *result, int index) {
    if (start >= end) return;
    for (int i = start; i < end; ++i) {
        if (i > start && nums[i] == nums[i-1]) continue;
        int newTarget = target - nums[i];
        for (int j = i + 1; j < end; ++j) {
            if (j > i + 1 && nums[j] == nums[j-1]) continue;
            int left = j + 1;
            int right = end - 1;
            while (left < right) {
                int sum = nums[j] + nums[left] + nums[right];
                if (sum == newTarget) {
                    result[index++] = nums[i];
                    result[index++] = nums[j];
                    result[index++] = nums[left];
                    result[index++] = nums[right];
                    ++left;
                    --right;
                    while(left < right && nums[left] == nums[left-1]) ++left;
                    while(left < right && nums[right] == nums[right+1]) --right;
                } else if (sum < newTarget) {
                    ++left;
                } else {
                    --right;
                }
            }
        }
    }
}

int** fourSum(int* nums, int numsSize, int target, int* returnSize, int** returnColumnSizes){
    qsort(nums, numsSize, sizeof(int), cmp);
    int resultCount = 0;
    int **results = malloc(sizeof(int*) * numsSize);
    int *tempResult = malloc(sizeof(int) * 4 * numsSize);
    for (int i = 0; i < numsSize; ++i) {
        if (i == 0 || nums[i] != nums[i-1]) {
            fourSumUtil(nums, numsSize, i + 1, numsSize, target, tempResult, resultCount);
            int currentResultIndex = resultCount;
            while(resultCount % 4 != 0) {
                results[currentResultIndex / 4] = &tempResult[currentResultIndex];
                ++currentResultIndex;
            }
        }
    }
    *returnSize = resultCount / 4;
    *returnColumnSizes = malloc(sizeof(int) * (*returnSize));
    for(int i = 0; i < (*returnSize); ++i) {
        (*returnColumnSizes)[i] = 4;
    }
    free(tempResult);
    return results;
}

Python

python 复制代码
def fourSum(nums, target):
    nums.sort()
    result = []
    quadruplets = []
    for i in range(len(nums)-3):
        if i > 0 and nums[i] == nums[i-1]:
            continue
        for j in range(i+1, len(nums)-2):
            if j > i+1 and nums[j] == nums[j-1]:
                continue
            l, r = j+1, len(nums)-1
            while l < r:
                total = nums[i] + nums[j] + nums[l] + nums[r]
                if total < target:
                    l += 1
                elif total > target:
                    r -= 1
                else:
                    result.append([nums[i], nums[j], nums[l], nums[r]])
                    while l < r and nums[l] == nums[l+1]:
                        l += 1
                    while l < r and nums[r] == nums[r-1]:
                        r -= 1
                    l += 1
                    r -= 1
    return result

Java

java 复制代码
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Solution {
    public List<List<Integer>> fourSum(int[] nums, int target) {
        Arrays.sort(nums);
        List<List<Integer>> results = new ArrayList<>();
        for (int i = 0; i < nums.length - 3; i++) {
            if (i != 0 && nums[i] == nums[i - 1]) continue;
            for (int j = i + 1; j < nums.length - 2; j++) {
                if (j != i + 1 && nums[j] == nums[j - 1]) continue;
                int left = j + 1, right = nums.length - 1;
                while (left < right) {
                    int sum = nums[i] + nums[j] + nums[left] + nums[right];
                    if (sum < target) {
                        left++;
                    } else if (sum > target) {
                        right--;
                    } else {
                        results.add(Arrays.asList(nums[i], nums[j], nums[left], nums[right]));
                        while (left < right && nums[left] == nums[left + 1]) left++;
                        while (left < right && nums[right] == nums[right - 1]) right--;
                        left++;
                        right--;
                    }
                }
            }
        }
        return results;
    }
}

时间复杂度

时间复杂度为 O(n^3),其中 n 是数组中的元素数量。这是因为我们需要遍历数组三次来找到所有可能的四元组。空间复杂度主要取决于结果列表的空间需求,最坏情况下为 O(n)。

相关推荐
小羊没烦恼!4 天前
微服务化的基石——持续集成
java·大数据·word·powerpoint·.net
倒头就睡的小比特4 天前
算法竞赛C++常用的STL
c++·算法
默_笙4 天前
🍙 给每个请求过安检:FastAPI 是怎么把校验写进类型注解的
python
俊昭喜喜里4 天前
java中的继承和多态的区别
java
小羊没烦恼!4 天前
初探性能优化——2个月到4小时的性能提升
java·开发语言·windows·算法·c#
qq_426003964 天前
启动playwright录制codegen生成自动化测试脚本
python·自动化
譕痕4 天前
JSONObject与JSONArray封装数据格式区别
java·json
虎头金猫4 天前
4K 视频总卡在公网带宽?用 N1 + OpenList 把网盘播放链路重新理顺
运维·服务器·网络·python·容器·beautifulsoup·pandas
胡写代码4 天前
别再前后端各写一套表单校验了
java·后端
小鱼能吃糖4 天前
缺陷修复总览 · mall电商项目:5类缺陷,1个病根,4个业务域
java·电商