public class Solution {
    public int FourSumCount(int[] A, int[] B, int[] C, int[] D) {
        var dic = new Dictionary<int, int>();

            for (int i = 0; i < C.Length; i++)
            {
                for (int j = 0; j < D.Length; j++)
                {
                    int sum = C[i] + D[j];
                    if (!dic.ContainsKey(sum))
                    {
                        dic.Add(sum, 1);
                    }
                    else
                    {
                        dic[sum]++;
                    }
                }
            }

            int res = 0;
            for (int i = 0; i < A.Length; i++)
            {
                for (int j = 0; j < B.Length; j++)
                {

                    var cur = 0;
                    var oppo = -1 * (A[i] + B[j]);
                    if (dic.ContainsKey(oppo))
                    {
                        cur = dic[oppo];
                    }
                    res += cur;
                }
            }

            return res;
    }
}

https://leetcode.com/problems/4sum-ii/#/description

 

补充一个python的版本:

 1 class Solution:
 2     def fourSumCount(self, A: 'List[int]', B: 'List[int]', C: 'List[int]', D: 'List[int]') -> int:
 3         partone = {}
 4         res = 0
 5         for a in A:
 6             for b in B:
 7                 cur = a + b
 8                 if cur in partone:
 9                     partone[cur] += 1
10                 else:
11                     partone[cur] = 1
12         
13         for c in C:
14             for d in D:
15                 cur = c + d
16                 if -cur in partone:
17                     res += partone[-cur]
18 
19         return res

 

posted on 2017-05-11 11:47  Sempron2800+  阅读(172)  评论(0编辑  收藏  举报