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
题目链接:https://leetcode.com/problems/4sum-ii/
解题思路
本题的解题思路来自于学习视频。
本题给出了明确的数据范围,因此可以从这个考虑算法复杂度。
暴力解法:O(n^4)使用4层循环,500^4=100多亿 > 10^8。
将一个数组存入查找表,复杂度下降:O(n^3),500^3=1亿多 > 10^8。
继续下降复杂度,需要再将一个数组的信息也放入查找表,因此把两个数组所有组合情况的和放入查找表:O(n^2)。
!问题的核心是找到需要查找的东西。
class Solution {
public:
int fourSumCount(vector<int>& A, vector<int>& B, vector<int>& C, vector<int>& D) {
unordered_map<int,int> record;
int res = 0;
for(int i=0;i<A.size();++i){
for (int j=0;j<B.size();++j){
record[A[i]+B[j]]++;
}
}
for(int i=0;i<C.size();++i){
for(int j=0;j<D.size();++j){
int tmp = C[i]+D[j];
if(record.find(0-tmp)!=record.end()){
res += record[0-tmp];
}
}
}
return res;
}
};
总结下数组里查找的题型的两个套路:
1.查找表 - 利用hash下降复杂度,但占空间大;
2.排序 - 利用有序性下降复杂度,一般适用在单个数组的题。
两条思路都需要结合复杂度考虑具体情况。