Problem Description:
Given an array of integers containing the list of four A, B, C, D, calculate how many tuples (i, j, k, l)
so A[i] + B[j] + C[k] + D[l] = 0
.
In order to simplify the problem, all of the A, B, C, D have the same length N, and 0 ≤ N ≤ 500. All integers in the range of -228 to 228-- between 1, the final result will not exceed 231--1.
E.g:
Input: A = [ 1, 2] B = [-2,-1] C = [-1, 2] D = [ 0, 2] Output: 2 Explanation: Two yuan groups were as follows: 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
The basic idea:
This question violence O (n ^ 4), is absolutely undesirable. So bipartite skills .
Traversing the first two lists , and get all of two numbers; after traversing two lists , all the numbers and get two; statistics both in the result set number of elements in each other's opposite number , is the answer.
So we reduced the complexity to O (n ^ 2) a.
But still TLE, so we thought by thought hash table to reduce complexity.
This is because the hash table insertion and query an element of the average time complexity is O (1);
(Others, such as the BST, inserts and queries are O (logn), ordinary Vector, upon insertion O (1), query O (n))
At the same time we can reduce the amount of code elements and immediate way to get the query .
AC Code:
class Solution {
public:
int fourSumCount(vector<int>& A, vector<int>& B, vector<int>& C, vector<int>& D) {
// 二分法降低复杂度
// 使用hashmap代表多重集,(合并处理和查询)降低查询时间复杂度
int n = A.size();
// 个人认为m是value_initialized的理由是一开始没法初始化
unordered_map<int, int> m; // 第一个元素代表元素值,第二个元素代表重复的次数
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
++m[A[i] + B[j]];
}
}
int count = 0;
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
count += m[-C[i] - D[j]];
}
}
return count;
}
};
Other experience:
- I have to say right son is still very reasonable, the Map is indeed much slower than unordered_map .
- If we need to use multiple sets, you can be simulated by using unorder_map its corresponding key value is the number of repeating elements.
- If the post-processing element to match, you can pass through the side edge matching approach to reduce complexity .