首页 > 代码库 > 【LeetCode】454 4Sum II
【LeetCode】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: 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
题解:
嗯,老规矩,直接暴力解,一共四个循环。
Solution 1 (TLE)
1 class Solution { 2 public: 3 int fourSumCount(vector<int>& A, vector<int>& B, vector<int>& C, vector<int>& D) { 4 sort(A.begin(), A.end()); 5 sort(B.begin(), B.end()); 6 sort(C.begin(), C.end()); 7 sort(D.begin(), D.end()); 8 int n = A.size(); 9 int cnt = 0; 10 for(int i=0; i<n; i++) { 11 for(int j=0; j<n; j++) { 12 for(int k=0; k<n; k++) { 13 for(int l=0; l<n; l++) { 14 int sum = A[i] + B[j] + C[k] + D[l]; 15 if(sum==0) { 16 cnt++; 17 } 18 else if(sum<0) continue; 19 else break; 20 } 21 } 22 } 23 } 24 return cnt; 25 } 26 };
不出意外,TLE了,哈哈。那怎么降低时间复杂度呢?我基本上第一时间想到的就是双指针和map(set),这个明显双指针一般用于单个数组的操作,因此可以考虑使用map。思路:使用两个循环,循环一:建立两个map,一个是AB两数组元素和与出现次数的map,另一个为CD两数组元素和与出现次数的map,循环二:遍历map1,map2使用find函数来查找是否存在遍历元素的相反数。
Solution 2 (706ms)
1 class Solution { 2 public: 3 int fourSumCount(vector<int>& A, vector<int>& B, vector<int>& C, vector<int>& D) { 4 unordered_map<int,int> m1, m2; 5 int result = 0; 6 int n = A.size(); 7 8 for(int i = 0; i < n; ++i) { 9 for(int j = 0; j < n; ++j) { 10 ++m1[A[i] + B[j]]; 11 ++m2[C[i] + D[j]]; 12 } 13 } 14 /* for(auto it = m1.begin(); it != m1.end(); ++it) { 15 if(m2.find(-it->first) != m2.end()) 16 result += it->second * m2[-it->first]; 17 } */ 18 for (auto p : m1) result += p.second * m2[-p.first]; 19 return result; 20 } 21 };
另一个解法也是利用两个循环,不过只使用一个map,建立AB两数组元素和与出现次数的map后,对CD遍历元素求和得opp,result += m[-opp],若-opp不存在,则m[-opp]为0,若存在,则result加上其出现的次数。
Solution 3 (449ms)
1 class Solution { 2 public: 3 int fourSumCount(vector<int>& A, vector<int>& B, vector<int>& C, vector<int>& D) { 4 int result = 0, n = A.size(); 5 unordered_map<int, int> m; 6 for (int i=0; i<n; ++i) { 7 for (int j=0; j<n; ++j) { 8 ++m[A[i] + B[j]]; 9 } 10 } 11 for (int i=0; i<n; ++i) { 12 for (int j=0; j<n; ++j) { 13 int opp = -1 * (C[i] + D[j]); 14 result += m[opp]; 15 } 16 } 17 return result; 18 } 19 };
【LeetCode】454 4Sum II