4sumII

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:
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
基本思路:利用2sum的思想,把A,B两者所有可能的和及其对应的个数保存起来,然后结合C,D的和去查找
 1 class Solution {
 2 public:
 3     int fourSumCount(vector<int>& A, vector<int>& B, vector<int>& C, vector<int>& D) {
 4         int count=0,len=A.size();
 5         map<int,int>  Mymap;
 6         for(int i=0;i<len;i++)
 7         {
 8             for(int j=0;j<len;j++)
 9             {
10                 Mymap[A[i]+B[j]]++;
11             }
12         }
13         for(int i=0;i<len;i++)
14             for(int j=0;j<len;j++)
15             {
16                 auto iter=Mymap.find(-C[i]-D[j]);
17                 if(iter!=Mymap.end())  count+=iter->second;
18             }
19         return count;
20     }
21 };

 

posted on 2017-10-09 19:53  wsw_seu  阅读(131)  评论(0编辑  收藏  举报

导航