[leetcode454] Four-number addition--go language implementation

Title description:

Given you four integer arrays nums1, nums2, nums3 and nums4, the length of the arrays is n, please calculate how many tuples (i, j, k, l) can satisfy:

0 <= i, j, k, l < n
nums1[i] + nums2[j] + nums3[k] + nums4[l] == 0

Example 1:

Input : nums1 = [1,2], nums2 = [-2,-1], nums3 = [-1,2], nums4 = [0,2]
Output : 2
Explanation : The two tuples are as follows:

  1. (0, 0, 0, 1) -> nums1[0] + nums2[0] + nums3[0] + nums4[1] = 1 + (-2) + (-1) + 2 = 0
  2. (1, 1, 0, 0) -> nums1[1] + nums2[1] + nums3[0] + nums4[0] = 2 + (-1) + (-1) + 0 = 0

Example 2:

Input : nums1 = [0], nums2 = [0], nums3 = [0], nums4 = [0]
Output : 1

Idea analysis:

Define the variable res to count the number of occurrences of a+b+c+d = 0. Traverse the first two arrays a and b, and put the sum of the elements and the number of occurrences into the map.
Then traverse the next two arrays c and d, if 0-(c+d)
has appeared in the map, use count to count the value corresponding to the key in the map, that is, the number of occurrences, add it to res, and finally return the statistics The value res is fine

specific code

func fourSumCount(nums1 []int, nums2 []int, nums3 []int, nums4 []int) int {
    
    
	hashmap1:=map[int]int{
    
    }
	res:=0
	for _,a:=range nums1{
    
    
		for _,b:=range nums2{
    
    
			hashmap1[a+b]++
		}
	}
	for _,c:=range nums1{
    
    
		for _,d:=range nums2{
    
    
			if count,ok:=hashmap1[0-c-d];ok{
    
    
				res+=count
			}
		}
	}
	return res
}

Guess you like

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