454. 4Sum II

仅供自己学习

 

思路:

如果暴力解,就是从A每个与B C D中的每一个元素相加,那么时间复杂度就是O(n^4)

如果用一个hash表,存储结果,每次值用O(1)的时间获取并相加,则可以优化到O(n^2)

我们用hash表存储A+B的结果,A+B的结果作为key值,然后value值就是计数有多少个这种结果的组合数。然后遍历C+D的所有可能,如果相反数能在该hash表找到,那么就加上该key的value,这就是最终的结果

 1 class Solution {
 2 public:
 3     int fourSumCount(vector<int>& A, vector<int>& B, vector<int>& C, vector<int>& D) {
 4         int res=0;
 5         unordered_map<int,int> mp;
 6         for(auto& a:A){
 7             for(auto& b:B){
 8                 ++mp[a+b];
 9             }
10         }
11         for(auto& c:C){
12             for(auto& d:D){
13                 if(mp.count(-c-d)){
14                     res+=mp[-c-d];
15                 }
16             }
17         }
18         return res;
19     }
20 };

 

posted @ 2021-03-09 16:58  Mrsdwang  阅读(37)  评论(0)    收藏  举报