第十八题:四数之和

题目描述

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

相关推荐
暗武逢天14 小时前
Java导出写入固定Excel模板数据
java·导出数据·easyexcel·excel固定模板导出
摇滚侠14 小时前
Spring Boot3零基础教程,KafkaTemplate 发送消息,笔记77
java·spring boot·笔记·后端·kafka
jiuri_121516 小时前
Docker使用详解:在ARM64嵌入式环境部署Python应用
python·docker·容器
chenchihwen16 小时前
AI代码开发宝库系列:Function Call
人工智能·python·1024程序员节·dashscope
fat house cat_17 小时前
【netty】基于主从Reactor多线程模型|如何解决粘包拆包问题|零拷贝
java·服务器·网络·netty
.格子衫.17 小时前
022数据结构之树状数组——算法备赛
数据结构·算法·1024程序员节
黑科技Python17 小时前
生活中的“小智慧”——认识算法
学习·算法·生活
Yupureki17 小时前
从零开始的C++学习生活 16:C++11新特性全解析
c语言·数据结构·c++·学习·visual studio
青云交17 小时前
Java 大视界 -- Java 大数据在智能教育学习社区互动模式创新与用户活跃度提升中的应用(426)
java·大数据·学习·flink 实时计算·智能教育社区·互动模式创新·用户活跃度