LeetCode算法题18:四数之和解析

给定一个包含 n 个整数的数组 nums 和一个目标值 target,判断 nums 中是否存在四个元素 a,b,c 和 d ,使得 a + b + c + d 的值与 target 相等?找出所有满足条件且不重复的四元组。

注意:
答案中不可以包含重复的四元组。

示例:

给定数组 nums = [1, 0, -1, 0, -2, 2],和 target = 0。

满足要求的四元组集合为:
[
  [-1,  0, 0, 1],
  [-2, -1, 1, 2],
  [-2,  0, 0, 2]
]

这个题和三数之和基本完全一样,就是多了一层循环,思路还是先对数组排序,然后确定一个,然后找剩余三个,剩余三个中先确定一个,另外两个用双指针。需要注意的是重复元素的排除。
C++源代码:

class Solution {
public:
    vector<vector<int>> fourSum(vector<int>& nums, int target) {
        vector<vector<int>> res;
        int n = nums.size();
        sort(nums.begin(), nums.end());
        for(int i=0;i<n-3;i++)
        {
            if(i>0 && nums[i]==nums[i-1]) continue;
            for(int j=i+1;j<n-2;j++)
            {
                if(j>i+1 && nums[j]==nums[j-1]) continue;
                int left = j+1, right = n-1;
                while(left<right)
                {
                    int fourSum = nums[i]+nums[j]+nums[left]+nums[right];
                    if(fourSum==target)
                    {
                        vector<int> one{nums[i], nums[j], nums[left], nums[right]};
                        res.push_back(one);
                        while(left<right && nums[left+1]==nums[left]) left++;
                        while(left<right && nums[right-1]==nums[right]) right--;
                        left++;
                        right--;
                    }
                    else if(fourSum<target) left++;
                    else right--;
                }
            }
        }
        return res;
    }
};

python3源代码:

class Solution:
    def fourSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[List[int]]
        """
        res = []
        n = len(nums)
        nums.sort()
        for i in range(n-3):
            if i>0 and nums[i]==nums[i-1]: continue
            for j in range(i+1, n-2):
                if j>i+1 and nums[j]==nums[j-1]: continue
                left = j+1
                right = n-1
                while left < right:
                    fourSum = nums[i] + nums[j] + nums[left] + nums[right]
                    if fourSum == target:
                        res.append([nums[i], nums[j], nums[left], nums[right]])
                        while left<right and nums[left+1]==nums[left]:
                            left += 1
                        while left<right and nums[right-1]==nums[right]:
                            right -= 1
                        left += 1
                        right -= 1
                    elif fourSum<target:
                        left += 1
                    else:
                        right -= 1
        return res

猜你喜欢

转载自blog.csdn.net/x603560617/article/details/84579734