LeetCode 4Sum (Two pointers)

题意

Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.
给定一个数组,找出其中的四个数,使它们的和等于某个特定的数

解法

和2Sum以及3Sum一样,都是先排序然后遍历前面几个数,剩下的两个数用Two Pointers来找,能降低一个N的复杂度,这里复杂度为O(N^3)

这里采用了一种比3Sum这题里更简洁的判重方法,直接将选出的数用Map记录,每次选取前检查一次Map看是否存在。虽然效率有所牺牲,但是代码变得很简洁而且有高可读性,自认为有些时候这种交换是值得的。

class Solution
{
public:
    vector<vector<int>> fourSum(vector<int>& nums, int target)
    {
	    vector<vector<int>>	rt;
	    map<vector<int>,bool>	map;

	    sort(nums.begin(),nums.end());

	    for(int i = 0;i < nums.size();i ++)
		    for(int j = i + 1;j < nums.size();j ++)
		    {
			    int k = j + 1;
			    int	l = nums.size() - 1;
			    while(k < l)
			    {
				    if(nums[i] + nums[j] + nums[k] + nums[l] == target)
				    {
					    vector<int>	temp = {nums[i],nums[j],nums[k],nums[l]};
					    if(map.find(temp) == map.end())
					    {
						    map[temp] = true;
						    rt.push_back(temp);
					    }
					    k ++;
				    }

				    else	if(nums[i] + nums[j] + nums[k] + nums[l] < target)
					    k ++;
				    else
					    l --;
			    }
		    }
	    return	rt;
        
    }
};
原文地址:https://www.cnblogs.com/xz816111/p/5857317.html