fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. int findPairs(vector<int>&arr , int k){
  5. unordered_map<int,int>mpp;
  6. int ans=0;
  7. for(int j=0;j<arr.size();j++){
  8. int comp1 = arr[j]-k;
  9. int comp2 = arr[j] + k;
  10. if(mpp.count(comp1)){
  11. ans += mpp[comp1];
  12. }
  13. if(k!=0 && mpp.count(comp2)){ // to avoid double counting when k = 0
  14. ans += mpp[comp2];
  15. }
  16. mpp[arr[j]]++;
  17. }
  18. return ans;
  19. }
  20.  
  21. int main() {
  22. int n;
  23. cin >> n;
  24. vector<int> arr(n);
  25.  
  26. for (int i = 0; i < n; i++) {
  27. cin >> arr[i];
  28. }
  29.  
  30. int k;
  31. cin>>k;
  32. cout<<findPairs(arr,k);
  33. return 0;
  34. }
  35.  
Success #stdin #stdout 0.01s 5288KB
stdin
4
2 2 2 2
0
stdout
6