Code : Pair Sum to 0
The first line of input contains an integer, that denotes the value of the size of the array. Let us denote it with the symbol N.
The following line contains N space separated integers, that denote the value of the elements of the array.
The first and only line of output contains the count of pair of elements in the array which sum up to 0.
0 <= N <= 10^4
Time Limit: 1 sec
5
2 1 -2 2 3
2
#include <unordered_map>int pairSum(int *arr, int n) { unordered_map<int, int> map; int mycount = 0; for (int i = 0; i < n; i++) { map[arr[i]]++; } mycount += map[0] * (map[0] - 1) / 2; map[0] = 0; for (int i = 0; i < n; i++) { if (map[-arr[i]] > 0) { mycount += map[arr[i]] * map[-arr[i]]; map[arr[i]] = 0; map[-arr[i]] = 0; } } return mycount;}
Comments
Post a Comment