[LeetCode] 18, and the number of four

Title Description

Given a n integer array numsand a target value target, it is determined numswhether there are four elements a, b, c and d, such that A + B + C + d value and targetequal to? Identify all satisfy the conditions of the quad and do not repeat.

给定数组 nums = [1, 0, -1, 0, -2, 2],和 target = 0。
满足要求的四元组集合为:
[
  [-1,  0, 0, 1],
  [-2, -1, 1, 2],
  [-2,  0, 0, 2]
]

Problem-solving ideas

Go CSDN search for "sum" , you can see a similar problem.

This question in 15, and triple the number of basis plus a layer of forcirculation, the idea is the same .

  • Sorting + double pointer :
    • Use four pointer (a<b<c<d). Fixed minimum aand bon the c=b+1left, d=_size-1, . Solving two pointers move sandwich. Save makes the nums[a]+nums[b]+nums[c]+nums[d]==targetsolution. When too large and dleft, when the small cright. cAnd dwhen met, expressed in current aand ba minimum value of all the solution has been obtained, b++into the next bcycle, when bthe end of the loop a++, the next one acycle. I.e., ( athe outermost loop, which is nested bloop, again nested double pointer c,dsandwiched Solution).
    • To use the double pointer method, the sort must be done der ~. time complexity O ( N l O g N ) O (nlogn) .
    • Solutions reason duplicate because the above solution is a repetitive number may occur when moving the pointer. After so we have to make sure to move the pointer,
      the corresponding number to change the job oh.

Reference Code

class Solution{
	public: 
	vector<vector<int>> fourSum(vector<int>& nums, int target) {
        vector<vector<int> > res;
        if(nums.size()<4)
            return res;
            
        sort(nums.begin(),nums.end());
        int a, b, c, d, _size = nums.size();
        for(a = 0; a <= _size-4; a++){
        	if(a > 0 && nums[a] == nums[a-1]) 
                continue;      //确保nums[a] 改变了
        	for(b = a+1; b <= _size-3; b++){
        		if(b > a+1 && nums[b] == nums[b-1])
                    continue;   //确保nums[b] 改变了
            
        		c = b + 1, d = _size - 1;
        		while(c < d){
        			if(nums[a]+nums[b]+nums[c]+nums[d] < target)
        			    c++;
        			else if(nums[a]+nums[b]+nums[c]+nums[d] > target)
        			    d--;
        			else{
        				res.push_back({nums[a], nums[b], nums[c], nums[d]});
        				while(c < d && nums[c+1]==nums[c])      //确保nums[c] 改变了
        				    c++;
        				while(c < d&&nums[d-1]==nums[d])      //确保nums[d] 改变了
        				    d--;
        				c++;
        				d--;
					}
				}
			}
		}
		
		return res;
    }
};
Published 415 original articles · won praise 603 · Views 150,000 +

Guess you like

Origin blog.csdn.net/ft_sunshine/article/details/104056232