Skip to content

Latest commit

 

History

History
49 lines (39 loc) · 1.19 KB

454.4sum-ii.md

File metadata and controls

49 lines (39 loc) · 1.19 KB

给定四个包含整数的数组列表  A , B , C , D ,计算有多少个元组 (i, j, k, l) ,使得  A[i] + B[j] + C[k] + D[l] = 0。

为了使问题简单化,所有的 A, B, C, D 具有相同的长度  N,且 0 ≤ N ≤ 500 。所有整数的范围在 -228 到 228 - 1 之间,最终结果不会超过  231 - 1 。

例如:

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

输出: 2

解释: 两个元组如下:

  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

来源:力扣(LeetCode) 链接:https://leetcode.cn/problems/4sum-ii 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。


借用 map,记录两个数组的和

var fourSumCount = function (A, B, C, D) {
  let map1 = new Map();
  for (let a of A) {
    for (let b of B) {
      let key = a + b;
      if (map1.has(key)) map1.set(key, map1.get(key) + 1);
      else map1.set(key, 1);
    }
  }
  let counter = 0;
  for (let c of C) {
    for (let d of D) {
      let key = c + d;
      if (map1.has(-key)) counter += map1.get(-key);
    }
  }
  return counter;
};