(Java)leetcode-454 4Sum II

Title Description

Adding the number four [II]
given integer array containing a list of four A, B, C, D, to calculate how many tuples (i, j, k, l ), such that A [i] + B [j ] + C [k] + D [ l] = 0.

In order to simplify the problem, all of the A, B, C, D have the same length N, and 0 ≤ N ≤ 500. All integers in the range of -228 to 228-- between 1, 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:
two yuan groups were 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

Thinking

This problem is most intuitive solution Violence Act, one by one to verify all positions, but the time complexity is O (n ^ 4), to submit the actual verification time out.
Look-up table may be employed to reduce the time complexity, reference leetcode the Sum-Two. 1 .
Only one double loop by A + B (two arrays are selected from any line) may be stored in each of the lookup table (map), key and is A + B, value is the number of occurrences.
And we just need to go through a double loop, there is no table to find the record -CD on the line, if so, because (A + B) + (C + D) = 0, which is consistent with conditions described one case, the total number of results can be updated.

Code

class Solution {
    public int fourSumCount(int[] A, int[] B, int[] C, int[] D) {
        Map<Integer, Integer> map = new HashMap<Integer, Integer>(); 
        for(int a : A)
            for(int b : B){
                int sum = a+b;
                map.put( sum, map.getOrDefault(sum, 0)+1 ); 
            }
        
        int result=0;
        for(int c : C)
            for(int d : D){
                int sum = -c-d;
                result += map.getOrDefault(sum, 0);
            }
        return result; 
    }
}

Present the results

Here Insert Picture Description

Published 143 original articles · won praise 45 · views 70000 +

Guess you like

Origin blog.csdn.net/z714405489/article/details/103182800