LeetCode18. 4Sum(C++/Python)

本文深入探讨了四数之和问题的解决方案,利用双指针法在已排序的数组中寻找四个数,使得它们的和等于目标值。通过详细的C++和Python代码示例,展示了如何避免重复解,确保解集的唯一性。

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

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

Note:

The solution set must not contain duplicate quadruplets.

Example:

Given array nums = [1, 0, -1, 0, -2, 2], and target = 0.

A solution set is:
[
  [-1,  0, 0, 1],
  [-2, -1, 1, 2],
  [-2,  0, 0, 2]
]

采用与15题相同的思路,只不过,这里是先确定两个数,然后用双指针法。

C++

class Solution {
public:
    vector<vector<int>> fourSum(vector<int>& nums, int target) {
        vector<vector<int>>result;
        sort(nums.begin(),nums.end());
        for(int i=0;i<nums.size();i++){
            for(int j=i+1;j<nums.size();j++){
                int low=j+1,high=nums.size()-1;
                int tempsum=-nums[i]-nums[j]+target;
                while(low<high){
                    if(nums[low]+nums[high]==tempsum){
                        vector<int>temp;
                        temp.push_back(nums[i]);temp.push_back(nums[j]);
                        temp.push_back(nums[low]);temp.push_back(nums[high]);
                        result.push_back(temp);
                        while(low<high&&nums[low+1]==nums[low])
                            low++;
                        low++;
                        while(low<high&&nums[high]==nums[high-1])
                            high--;
                        high--;
                    }
                    else if(nums[low]+nums[high]<tempsum)
                        low++;
                    else
                        high--;
                }
                while(j<nums.size()-1&&nums[j]==nums[j+1])
                    j++;
            }
            while(i<nums.size()-1&&nums[i]==nums[i+1])
                    i++;
        }
        return result;
    }
};

Python

class Solution(object):
    def fourSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[List[int]]
        """
        ans = []
        if len(nums) < 4:
            return ans
        nums.sort()
        for i in range(len(nums)):
            if i != 0 and nums[i] == nums[i-1]:
                continue
            for j in range(i+1, len(nums)):
                if j != i+1 and nums[j] == nums[j-1]:
                    continue
                low, high = j+1, len(nums)-1
                temp = nums[i] + nums[j]
                while low < high:
                    tempsum = temp + nums[low] + nums[high]
                    if tempsum == target:
                        ans.append([nums[i], nums[j], nums[low], nums[high]])
                        while low < high and nums[low] == ans[-1][2]:
                            low += 1
                    elif tempsum > target:
                        high -= 1
                    else:
                        low += 1
        return ans     

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值