-
Notifications
You must be signed in to change notification settings - Fork 0
/
090_ZeroPairSum.cpp
46 lines (37 loc) · 923 Bytes
/
090_ZeroPairSum.cpp
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
46
#include<bits/stdc++.h>
using namespace std;
int ZeroPairSum(int n, vector<int> arr){
// Write your code here
// method-1
int count=0;
// for(int i=0; i<n; i++){
// for(int j=i+1; j<n; j++){
// int sum=arr[i]+arr[j];
// if(!sum) count++;
// }
// }
// method-2;
// unordered_map<int, int> seen;
// for(auto num: arr){
// if(seen[0-num]) count+=seen[0-num];
// seen[num]++;
// }
// method-3
unordered_map<int, int> pos;
unordered_map<int, int> neg;
for(auto num: arr){
if(num>=0){
pos[num]++;
}else{
neg[num]++;
}
}
for(auto item: pos){
if(item.first==0){
count+=(item.second*(item.second-1)/2);
}else{
count+=(item.second)*(neg[-item.first]);
}
}
return count;
}