diff --git a/README.md b/README.md index 8972471..3376db8 100644 --- a/README.md +++ b/README.md @@ -291,6 +291,7 @@ My LeetCode solutions with Chinese explanation. 我的LeetCode中文题解。 | 447 |[Number of Boomerangs](https://leetcode.com/problems/number-of-boomerangs)|[C++](https://github.com/ShusenTang/LeetCode/blob/master/solutions/447.%20Number%20of%20Boomerangs.md)|Easy| | | 448 |[Find All Numbers Disappeared in an Array](https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array)|[C++](https://github.com/ShusenTang/LeetCode/blob/master/solutions/448.%20Find%20All%20Numbers%20Disappeared%20in%20an%20Array.md)|Easy| | | 453 |[Minimum Moves to Equal Array Elements](https://leetcode.com/problems/minimum-moves-to-equal-array-elements)|[C++](https://github.com/ShusenTang/LeetCode/blob/master/solutions/453.%20Minimum%20Moves%20to%20Equal%20Array%20Elements.md)|Easy| | +| 454 |[4Sum II](https://leetcode.com/problems/4sum-ii/)|[C++](solutions/454.%204Sum%20II.md)|Medium| | | 455 |[Assign Cookies](https://leetcode.com/problems/assign-cookies)|[C++](https://github.com/ShusenTang/LeetCode/blob/master/solutions/455.%20Assign%20Cookies.md)|Easy| | | 459 |[Repeated Substring Pattern](https://leetcode.com/problems/repeated-substring-pattern)|[C++](https://github.com/ShusenTang/LeetCode/blob/master/solutions/459.%20Repeated%20Substring%20Pattern.md)|Easy| | | 461 |[Hamming Distance](https://leetcode.com/problems/hamming-distance)|[C++](https://github.com/ShusenTang/LeetCode/blob/master/solutions/461.%20Hamming%20Distance.md)|Easy| | diff --git a/solutions/454. 4Sum II.md b/solutions/454. 4Sum II.md new file mode 100644 index 0000000..9b0e4fa --- /dev/null +++ b/solutions/454. 4Sum II.md @@ -0,0 +1,37 @@ +# [454. 4Sum II](https://leetcode.com/problems/4sum-ii/) + +# 思路 + +从四个数组中各取一个数字,使其和为0,问有多少种取法。如果暴力四重循环的话复杂度为O(n^4),是不可接受的。 我们可以采用hashmap将前两个数组的元素的和存放起来,这样就可以将复杂度降至O(n^2)。 + +注意如果某个元素不在hashmap中,如果我们访问了它,那它会被插入到hashmap中,例 +``` C++ +unordered_mapmp; +int a = mp[2]; +if(mp.count(2)) cout << "2 is in mp!" ; // 会输出 +``` + + +# C++ +``` C++ +class Solution { +public: + int fourSumCount(vector& A, vector& B, vector& C, vector& D) { + int res = 0; + unordered_mapabSum; + for(int a: A) + for(int b: B) + abSum[a+b]++; + + for(int c: C) + for(int d: D){ + // 以下两行比直接 res += abSum[-c-d] 要快, + // 因为如果 -c-d 不在abSum中, 访问abSum[-c-d]会将-c-d插入abSum中 + auto it = abSum.find(-c-d); + if(it != abSum.end()) res += it -> second; + } + + return res; + } +}; +``` \ No newline at end of file