-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathforSum2.cpp
More file actions
45 lines (36 loc) · 1.18 KB
/
forSum2.cpp
File metadata and controls
45 lines (36 loc) · 1.18 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#include <iostream>
#include <vector>
#include <unordered_map>
// leetcode 454. 4Sum II
// Given four integer arrays v1, v2, v3, and v4 all of length n, return the number of tuples (i, j, k, l) such that:
// 0 <= i, j, k, l < n
// nums1[i] + nums2[j] + nums3[k] + nums4[l] == 0
class Solution
{
using vec = const std::vector<int>;
public:
int fourSumCount(vec& v1, vec& v2, vec& v3, vec& v4)
{
unsigned int result {0};
std::unordered_map<int, int> map;
const size_t size {v1.size()};
// nums1[i] + nums2[j] = -(nums3[k] + nums4[l])
for(int i{0}; i<size; i++)
for(int j{0}; j<size; j++)
map[v1[i] + v2[j]]++;
for(int i{0}; i<size; i++)
for(int j{0}; j<size; j++)
result = result + map[-(v3[i] + v4[j])];
return result;
}
};
int main()
{
std::vector<int> vec1 {1,2};
std::vector<int> vec2 {-2,-1};
std::vector<int> vec3 {-1,2};
std::vector<int> vec4 {0,2};
std::cout<<Solution{}.
fourSumCount(vec1, vec2, vec3, vec4)<<std::endl;
return 0;
}