4Sum II LeetCode solution in C++

1
class Solution {
2
public:
3
int fourSumCount(vector<int> &nums1, vector<int> &nums2, vector<int> &nums3, vector<int> &nums4) {
4
int count = 0;
5
unordered_map<int, int> mp;
6

7
/* Philosophy
8

9
1. I know that Addtion have two parts in it EG (a +b , Part 1 - a, Part 2-
10
b. 2.So, Lets make and find this dependency factors. How can I do it?
11

12
3. If there are 4 Sum. it means 2 sums is going to Part 1 and another 2
13
gonna be Part 2 which are dependent on Part 1 for 0 resultant.
14

15
4. I gonna store summation 2 nums1 in a FREQUENCY Hashmap.
16

17
5. Then I traverse 2nd part of the summation (rest to nums) and keep
18
checking that do (0-it1-it2) is exist in map .
19

20
6. If yes, the add the frequency of Part1 int COUNT var.
21

22
7. return count;
23
*/
24

25
// Traversing Part 1
26
for (auto &it1 : nums1)
27
for (auto &it2 : nums2) mp[it1 + it2]++;
28

29
// Traversing Part 2
30
for (auto &it3 : nums3)
31
for (auto &it4 : nums4)
32
if (mp.count(0 - it3 - it4)) count += mp[0 - it3 - it4];
33

34
return count;
35
}
36
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0