码迷,mamicode.com
首页 > 其他好文 > 详细

4sumII

时间:2017-10-09 20:50:41      阅读:140      评论:0      收藏:0      [点我收藏+]

标签:auto   col   思路   tuple   find   color   value   sam   amp   

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 };

 

4sumII

标签:auto   col   思路   tuple   find   color   value   sam   amp   

原文地址:http://www.cnblogs.com/wsw-seu/p/7642711.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!