leetcode18:4Sum(15-10-6)

一.题目

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

Note:

  • Elements in a quadruplet (a,b,c,d) must be in non-descending order. (ie, a ≤ b ≤ c ≤ d)
  • The solution set must not contain duplicate quadruplets.

    For example, given array S = {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)

二.思路

其实和前面3sum思路差不多,先对数组进行排序,然后分别用两个指针来固定两个元素nums[i],nums[j],再对剩下的两个元素求和,与target-nums[i]-nums[j]进行比较,知道找到相等的为止。

时间复杂度为O(N^3).

三.代码(在3sum基础上延伸过来)

class Solution {
public:
    vector<vector<int>> fourSum(vector<int>& nums, int target) {
       int size=nums.size();
	   vector<vector<int>> result;
	   if (size<4) return result;
	   sort(nums.begin(),nums.end());
	   for(int i=0;i<size;i++)
	   {
		   if(i>0 && nums[i]==nums[i-1]) continue;  //a
		   int tempTarget1=target-nums[i];
			for(int j=i+1;j<size;j++)
			{
				if(j>i+1 && nums[j]==nums[j-1]) continue;   //b
				int tempTarget2=tempTarget1-nums[j];
				int front=j+1,rear=size-1;
				while(rear>front)
				{
					if(front>j+1 && nums[front] == nums[front-1])  //c
					{
						front++;
						continue;
					}
					if(rear<size-1 && nums[rear] == nums[rear+1])     //d
					{
						rear--;
						continue;
					}
					int sum=nums[rear]+nums[front];
					if(sum>tempTarget2) rear--;
					else if(sum<tempTarget2) front++;
					else
					{
						vector<int> temp;
						temp.push_back(nums[i]);
						temp.push_back(nums[j]);
						temp.push_back(nums[front]);
						temp.push_back(nums[rear]);
						result.push_back(temp);
						front++;rear--;
					}
				}
			}
	   }
	   return result;
    }
};



注意几个关键的地方:a,b,c,d这样处理就可以避免重复。





你可能感兴趣的:(leetcode18:4Sum(15-10-6))