fork download
  1. #include<bits/stdc++.h>
  2. #include <iostream>
  3. using namespace std;
  4.  
  5. int countPair(vector<int> arr,int k){
  6. unordered_map<int,int> freq;
  7. int count=0;
  8. for(int i=0;i<arr.size();i++){
  9.  
  10. if(freq.find(arr[i]+k) != freq.end()){
  11. count = count+freq[arr[i]+k];
  12. }
  13. if(freq.find(arr[i]-k)!=freq.end() && k!=0){
  14. count += freq[arr[i]-k];
  15. }
  16.  
  17. freq[arr[i]]++;
  18.  
  19. }
  20. return count;
  21.  
  22. }
  23.  
  24. int main(){
  25. vector<int> arr={1, 5, 3, 4, 2};
  26. int k=2;
  27. cout<<"No. of Pairs: "<<countPair(arr,k);
  28. }
Success #stdin #stdout 0s 5324KB
stdin
Standard input is empty
stdout
No. of Pairs: 3