454. 4Sum II

网友投稿 751 2022-09-04

454. 4Sum II

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:2Explanation:The two tuples are:1. (0, 0, 0, 1) -> A[0] + B[0] + C[0] + D[1] = 1 + (-2) + (-1) + 2 = 02. (1, 1, 0, 0) -> A[1] + B[1] + C[0] + D[0] = 2 + (-1) + (-1) + 0 = 0

思路: 将四数转变为两个部分,首先遍历AB的组合(任意两个都可以),存下他们组合后的和的情况,然后遍历CD(另外两个)的和,看之前AB遍历的组合里有没有与此时值相反的值,有的话就加上AB中这个相反数出现的次数。

class Solution { public int fourSumCount(int[] A, int[] B, int[] C, int[] D) { int n = A.length; if( n == 0 ) return 0; HashMap ab = new HashMap(); for(int a:A){ for(int b:B){ ab.put(a + b,ab.getOrDefault(a + b,0) + 1); } } int res = 0; for(int c:C){ for(int d:D){ int part2 = c + d; int part1 = - part2; res += ab.getOrDefault(part1,0); } } return res; }}

/** * @param {number[]} A * @param {number[]} B * @param {number[]} C * @param {number[]} D * @return {number} */var fourSumCount = function(A, B, C, D) { const N = A.length if (!N) { return 0 } let count = 0 const map = new Map() for (let i = 0; i < N; i++) { for (let j = 0; j < N; j++) { const sum = C[i] + D[j] if (!map.has(sum)) { map.set(sum, 1) } else { map.set(sum, map.get(sum) + 1) } } } for (let i = 0; i < N; i++) { for (let j = 0; j < N; j++) { const sumCD = 0 - A[i] - B[j] if (map.has(sumCD)) { count += map.get(sumCD) } } } return count};

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:数据库分库分表,何时分?怎样分?(数据库分表的方法)
下一篇:57. Insert Interval
相关文章

 发表评论

暂时没有评论,来抢沙发吧~