Problem solving with programming: Finding the number of pairs in array with given difference
X. Sort first
No need visited array, remove from set directly.
Given an array of N distinct values, how to find the number of pairs with a difference of K?
X. Sort first
- Take two indices and point them to first and second elements.
- Repeat the following steps until any index reaches the end of the array
- If the difference matches, increment count and increment both the indices
- If the difference is less than required value, increment second index
- Otherwise increment first index.
X. Use HashSet ==< if not distinct, then use HashMap.int findPairsWithDiff( vector<int> &array, int diff ){sort( array.begin(), array.end() );int matches = 0;int size = array.size();if ( size > 1){int i,j;i = 0;j = 1;while ( i < size && j < size ){if( i != j && (array[j]-array[i]) == diff ){matches++;i++; // if not distinct, use while lopp to skip same element same as i,jj++;}else if( (array[j]-array[i]) < diff )j++;elsei++;}}return matches;}
No need visited array, remove from set directly.
- Store all the array elements into a set.
- For each element in the array do the following.
- If the set contains array[i]+diff or array[i]-diff, increment the diff count.
- Remove array[i] from the set.
Read full article from Problem solving with programming: Finding the number of pairs in array with given differenceint findPairsWithDiff1( vector<int> &array, int diff ){int matches = 0;int size = array.size();if ( size > 1){set<int> numSet;for( int i = 0; i < size; i++ ){numSet.insert(array[i]);}for( int i = 0; i < size; i++ ){if( numSet.find(array[i]+diff) != numSet.end() ||numSet.find(array[i]-diff) != numSet.end()){matches++;}numSet.erase( numSet.find(array[i]) );}}return matches;}