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. int complement=k-arr[i];
  10. if(freq.find(complement) != freq.end()){
  11. count = count+freq[complement];
  12. }
  13.  
  14. freq[arr[i]]++;
  15.  
  16. }
  17. return count;
  18.  
  19. }
  20.  
  21. int main(){
  22. vector<int> arr={1, 5, 7, -1, 5};
  23. int k=6;
  24. cout<<"No. of Pairs: "<<countPair(arr,k);
  25. }
Success #stdin #stdout 0s 5316KB
stdin
Standard input is empty
stdout
No. of Pairs: 3