LeetCode18:四数之和(Medium)

题目描述:

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

这个跟三数之和的思维一样的,就是多添加了个for循环,用了四个指针

c++实现:

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

猜你喜欢

转载自blog.csdn.net/Mr_xuexi/article/details/84258180