[leetcode18] The sum of four numbers -- go language implementation

Title description:

You are given an array nums of n integers, and a target value target. Please find and return quadruples [nums[a], nums[b], nums[c], nums[d]] that meet all the following conditions and are not repeated (if two quadruple elements correspond one-to-one , the two quadruples are considered repeated):

0 <= a, b, c, d < n
a、b、c 和 d 互不相同
nums[a] + nums[b] + nums[c] + nums[d] == target

You can return answers in any order.

Example 1:

Input : nums = [1,0,-1,0,-2,2], target = 0
Output : [[-2,-1,1,2],[-2,0,0,2],[ -1,0,0,1]]

Example 2 :

Input : nums = [2,2,2,2,2], target = 8 Output: [[2,2,2,2]]

Idea realization:

The sum of four numbers and 15. The sum of three numbers (opens new window) is the same idea, both of which use the double pointer method.
The basic solution is to add another layer on the basis of 15. The sum of three numbers (opens new window) for loop. For 15. The sum of three numbers (opens new window) the double pointer method is to convert the original violent O ( n 3 ) O(n^3)O ( n3 )solution, reduced toO ( n 2 ) O(n^2)O ( n2 )solution, the double pointer solution of the sum of four numbers is to convert the original violentO ( n 4 ) O(n^4)O ( n4 )solution, reduced toO ( n 3 ) O(n^3)O ( n3 )solution.

Code:

func fourSum(nums []int, target int) [][]int {
    
    
	res:=[][]int{
    
    }
	lens:=len(nums)
	if lens<=3{
    
    
		return res
	}
	sort.Ints(nums)
	if target>0&&nums[0]>=target{
    
    //如果第一个大于target,不满足,
		return res
	}
	if target<0&&nums[lens-1]<=target{
    
    //如果第一个大于target,不满足
		return res
	}
	for i:=0;i<lens-2;i++{
    
    
		if target>0&&nums[i]>=target{
    
    //退出条件
			break
		}
		if i>0&&nums[i]==nums[i-1]{
    
    //去重处理
			continue
		}
		for j:=i+1;j<lens-1;j++{
    
    
			
			if j!=i+1&&nums[j]==nums[j-1]{
    
    //去重处理
				continue
			}
			k,l:=j+1,lens-1
			for k<l{
    
    
				if k!=j+1&&nums[k]==nums[k-1]{
    
    
                    k++
					continue
				}
				if l!=lens-1&&nums[l]==nums[l+1]{
    
    
                    l--
					continue
				}
				if nums[i]+nums[j]+nums[k]+nums[l]<target{
    
    
					k++
				}else if nums[i]+nums[j]+nums[k]+nums[l]>target{
    
    
					l--
				}else {
    
    
					temp:=[]int{
    
    nums[i],nums[j],nums[k],nums[l]}
					res=append(res,temp)
					k++
					l--
				}
			}
		}
	}
	return res
}

Guess you like

Origin blog.csdn.net/weixin_42918559/article/details/125113367