Given an array, I've to find the index of pairs whose sum is equal to x.
Suppose the array is arr[5] = 1 2 3 4 2
and sum = 5, then the pairs are (1,4), (2,3) and (3,2).
I need to store indices of pairs which are for
(1,4) => (0,3)
(2,3) => (1,2)
(3,2) => (2,4)
So the answer is: (0,3),(1,2),(2,4)
I'm using hash map. Here's my function:
pair<int,int> index[5];
int FindPairs(int arr[],int n, int sum) {
int i, temp,count=0,seta[n],setb[n],j;
bool hash[MAX] = {0};
for(i = 0; i < n; ++i) {
temp = sum - arr[i];
if(temp >= 0 && hash[temp] == 1 )
seta[count++] = i;
hash[arr[i]] = 1;
}
if(count == 0) return 0;
for(i=0;i<count;++i){
for(j=0;j<n;j++){
if( (sum - arr[seta[i]]) ==arr[j] ) {
setb[i] = j;
break;
}
}
}
for(i=0;i<count;++i) index[i] = make_pair(seta[i],setb[i]);
return count;
}
Here:
n
is the size of array,seta[]
consists of index of first number in the pair andsetb[]
consists of index of second number in the pair.
I'm using O(count*n)
for calculating the index of second number for every pair.
Is there any more efficient way to achieve this?