C++ daily practice 26-addition of four numbers II

Addition of Four Numbers II
Given four array lists A , B , C , D containing integers, count how many tuples (i, j, k, l) there are such that A[i] + B[j] + C [k] + D[l] = 0.

To simplify the problem, all A, B, C, D have the same length N, and 0 ≤ N ≤ 500. All integers are in the range -228 to 228 - 1, and the final result will not exceed 231 - 1.

E.g:

Input: A = [ 1, 2] B = [-2,-1] C = [-1, 2] D = [ 0, 2]

Output: 2

Explanation: The two tuples are as follows:

  1. (0, 0, 0, 1) -> A[0] + B[0] + C[0] + D[1] = 1 + (-2) + (-1) + 2 = 0
  2. (1, 1, 0, 0) -> A[1] + B[1] + C[0] + D[0] = 2 + (-1) + (-1) + 0 = 0

Source: LeetCode
link: https://leetcode-cn.com/problems/4sum-ii The
overall idea
is to use the result of adding the first two numbers to build a hash table and record the number of repeated elements. The table is used to determine whether the negative number of the last two numbers and the key are added to 0, and the sum of the number of elements can be recorded.
C++ code:

class Solution {
    
    
public:
	int fourSumCount(vector<int>& A, vector<int>& B, vector<int>& C, vector<int>& D) {
    
    
		unordered_map<int, int> mapAB;
		int ret = 0;
		for (int& n1 : A) {
    
    
			for (int& n2 : B) {
    
    //构建哈希表
				if (mapAB.find(n1 + n2) == mapAB.end()) {
    
    
					mapAB[n1 + n2] = 1;
				}
				else {
    
    
					mapAB[n1 + n2]++;
				}
			}
		}
		for (int& n3 : C) {
    
    
			for (int& n4 : D) {
    
    
				if (mapAB.find(-n3-n4) != mapAB.end()) {
    
    //查询是否能存在相加为0的key
					ret += mapAB[-n3 - n4];
				}
			}
		}
		return ret;
	}
};

JAVA code

class Solution {
    
    
    public int fourSumCount(int[] A, int[] B, int[] C, int[] D) {
    
    
        int ret=0;
        Map<Integer,Integer> mapAB=new HashMap<Integer, Integer>();
        for(int n1:A){
    
    
            for(int n2:B){
    
    
                mapAB.put(n1+n2,mapAB.getOrDefault(n1 + n2, 0) + 1);
            }
        }
        for (int n3 : C) {
    
    
            for (int n4 : D) {
    
    
                if (mapAB.containsKey(-n3 - n4)) {
    
    
                    ret += mapAB.get(-n3 - n4);
                }
            }
        }
        return ret;
    }
}

Complexity analysis
Time complexity: O(n^2) n is the length of the array
Space complexity: O(n^2)

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324229533&siteId=291194637