LeetCode题解 -- 双指针(18)

本文深入探讨了四数之和算法,详细介绍了如何在给定整数数组中找到所有唯一四元组,使其和等于目标值。文章阐述了算法的时间复杂度为O(n^3),空间复杂度为O(1),并提供了特殊用例分析及Java实现代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

4Sum

Given an array nums of n integers and an integer target, are there elements a, b, c, and d in nums such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.

时间复杂度:O(n^3)
空间复杂度:O(1)

三个数的时候,当确定第一个数字后,第一个数字能不与其前一个的数字相同,否则结果一定重复。

四个数的时候,确定第一个数字后,也要保证第一个数字不能与其前一个数字相同,但是第二个数没有该限制,即可以存在第一个数 = 第二个数的情况 (但是要保证j - i != 1 时,第二个数不能和前面的重复)

特殊用例:
1.{0,0,0,0}
2.{-1,0,0,0,0,1}
3.{-1,-1,-1,-1,3}

class Solution {
    public List<List<Integer>> fourSum(int[] nums, int target) {
        int length = nums.length;
        if(length < 4)
            return new ArrayList<>();
        Arrays.sort(nums);
        List<List<Integer>> resultList = new ArrayList<>();

        for(int i = 0;i < length - 3;i++){
            if(i > 0 && nums[i] == nums[i - 1]){
                continue;
            }
            for(int j = i + 1;j < length - 2;j++){
                if(nums[j] == nums[j - 1] && j - i != 1){
                    continue;
                }
                int tempSum = nums[i] + nums[j];
                int start = j + 1;
                int end = length - 1;
                while(start < end){
                    int temp = tempSum;
                    temp = temp + nums[start] + nums[end];
                    if(temp == target){
                        resultList.add(Arrays.asList(nums[i],nums[j],nums[start],nums[end]));
                        start++;
                        end--;
                        while(start < end && nums[start] == nums[start - 1]){
                            start++;
                        }
                        while(start < end && nums[end] == nums[end + 1]){
                            end--;
                        }
                    }else if(temp > target){
                        end--;
                    }else{
                        start++;
                    }
                }
            }
        }
        return resultList;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值