要求
- 给出四个整型数组ABCD,寻找有多少 i j k l 的组合,使得A[i]+B[j]+C[k]+D[l]=0
- ABCD元素个数均为N,0<=N<=500
示例
- 输入:
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
思路
- 暴力解法,遍历A+B+C+D(n4,约63亿次运算)
- 将D中元素放入查找表,遍历A+B+C(n3,约1.25亿次运算,一般计算机难以在1s内完成)
- 将C+D的每一种可能放入查找表,遍历A+B(n2,25万个元素的查找表,25万次运算)
- 和可能重复,使用map,记录每个和出现了多少次
1 class Solution { 2 public: 3 int fourSumCount(vector<int>& A, vector<int>& B, vector<int>& C, vector<int>& D) { 4 5 unordered_map<int,int> record; 6 for( int i = 0 ; i < C.size() ; i ++ ) 7 for( int j = 0 ; j < D.size() ; j ++ ) 8 record[ C[i] + D[j] ] ++; 9 10 int res = 0; 11 for( int i = 0 ; i < A.size() ; i ++ ) 12 for( int j = 0 ; j < B.size() ; j ++ ) 13 if( record.find( 0 - A[i] -B[j] ) != record.end() ) 14 res += record[ 0 - A[i] -B[j] ]; 15 16 return res; 17 } 18 };
相关
- 49 Group Anagrams