第十八题:四数之和

题目描述

给定一个包含 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 小时前
【深度长文】万字攻克网络原理:从 HTTP 报文解构到 HTTPS 终极加密逻辑
java·开发语言·网络·python·http·ai·https
你撅嘴真丑6 小时前
第九章-数字三角形
算法
曹牧6 小时前
Spring Boot:如何测试Java Controller中的POST请求?
java·开发语言
uesowys7 小时前
Apache Spark算法开发指导-One-vs-Rest classifier
人工智能·算法·spark
ValhallaCoder7 小时前
hot100-二叉树I
数据结构·python·算法·二叉树
董董灿是个攻城狮7 小时前
AI 视觉连载1:像素
算法
爬山算法7 小时前
Hibernate(90)如何在故障注入测试中使用Hibernate?
java·后端·hibernate
智驱力人工智能7 小时前
小区高空抛物AI实时预警方案 筑牢社区头顶安全的实践 高空抛物检测 高空抛物监控安装教程 高空抛物误报率优化方案 高空抛物监控案例分享
人工智能·深度学习·opencv·算法·安全·yolo·边缘计算
kfyty7257 小时前
集成 spring-ai 2.x 实践中遇到的一些问题及解决方案
java·人工智能·spring-ai
猫头虎8 小时前
如何排查并解决项目启动时报错Error encountered while processing: java.io.IOException: closed 的问题
java·开发语言·jvm·spring boot·python·开源·maven