LeetCode 454 4Sum II

题目

Given four lists A, B, C, D of integer values, compute how many tuples (i, j, k, l) there are such that A[i] + B[j] + C[k] + D[l] is zero.

To make problem a bit easier, all A, B, C, D have same length of N where 0 ≤ N ≤ 500. All integers are in the range of -228 to 228 - 1 and the result is guaranteed to be at most 231 - 1.

Example:

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

Output:
2

Explanation:
The two tuples are:
(0, 0, 0, 1) -> A[0] + B[0] + C[0] + D[1] = 1 + (-2) + (-1) + 2 = 0
(1, 1, 0, 0) -> A[1] + B[1] + C[0] + D[0] = 2 + (-1) + (-1) + 0 = 0


解法思路(一)

  • 用四重循环,做一个 O(N4) 的解法,在 5004 的数量级的情况下肯定是跑不完的;
  • N = 500 的话,用 O(N2) 的时间复杂度的解法去跑是可行的;
如何实现一个 O(N2) 的解法呢?
  • 如果把 C 和 D 两两组合之和存进一个 HashMap 中,key 是两两组合之和,value 是该和出现的次数,这个动作的时间复杂度是 O(N2);
  • 那么 A 和 B 的两两组合之和去这个 HashMap 中匹配,这个匹配的动作是 O(1) 的,而 A 和 B 的两两组合之和是 O(N2) 的,则总的时间复杂度是 O(2N2) = O(N2);

解法实现(一)

时间复杂度
  • O(N2);
空间复杂度
  • O(N2)
关键字

查找表 HashMap 二维将一维 O(N^2) 降 O(1)

package leetcode._454;

import java.util.HashMap;

public class Solution454_1 {

    public int fourSumCount(int[] A, int[] B, int[] C, int[] D) {

        HashMap CDCombination = new HashMap<>(C.length * D.length);
        for (int i = 0; i < C.length; i++) {
            for (int j = 0; j < D.length; j++) {
                int CDAdd = C[i] + D[j];
                if (CDCombination.containsKey(CDAdd)) {
                    CDCombination.put(CDAdd, CDCombination.get(CDAdd) + 1);
                } else {
                    CDCombination.put(CDAdd, 1);
                }
            }
        }

        int combination = 0;
        for (int i = 0; i < A.length; i++) {
            for(int j = 0; j < B.length; j++) {
                int complement = 0 - A[i] - B[j];
                if (CDCombination.containsKey(complement)) {
                    combination += CDCombination.get(complement);
                }
            }
        }

        return combination;
    }

    public static void main(String[] args) {
        int[] A = {1, 2};
        int[] B = {-2, -1};
        int[] C = {-1, 2};
        int[] D = {0, 2};

        int result = (new Solution454_1()).fourSumCount(A, B, C, D);;
        System.out.println(result);
    }

}

返回 LeetCode [Java] 目录

你可能感兴趣的:(LeetCode 454 4Sum II)