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