第十八题:四数之和

题目描述

给定一个包含 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)。

相关推荐
迷迭所归处5 分钟前
C++ —— 关于vector
开发语言·c++·算法
架构文摘JGWZ33 分钟前
Java 23 的12 个新特性!!
java·开发语言·学习
FreakStudio34 分钟前
全网最适合入门的面向对象编程教程:50 Python函数方法与接口-接口和抽象基类
python·嵌入式·面向对象·电子diy
leon62534 分钟前
优化算法(一)—遗传算法(Genetic Algorithm)附MATLAB程序
开发语言·算法·matlab
CV工程师小林34 分钟前
【算法】BFS 系列之边权为 1 的最短路问题
数据结构·c++·算法·leetcode·宽度优先
Navigator_Z1 小时前
数据结构C //线性表(链表)ADT结构及相关函数
c语言·数据结构·算法·链表
还听珊瑚海吗1 小时前
数据结构—栈和队列
数据结构
Aic山鱼1 小时前
【如何高效学习数据结构:构建编程的坚实基石】
数据结构·学习·算法
拾光师1 小时前
spring获取当前request
java·后端·spring
aPurpleBerry1 小时前
neo4j安装启动教程+对应的jdk配置
java·neo4j