fork download
  1. #include <iostream>
  2. #include <unordered_map>
  3. #include <vector>
  4.  
  5. using namespace std;
  6.  
  7. int countPairsWithDifferenceK(const vector<int>& b, int k) {
  8. unordered_map<int, int> freq;
  9. int count = 0;
  10.  
  11. for (int j = 0; j < b.size(); ++j) {
  12. if (freq.find(b[j] - k) != freq.end()) {
  13. count += freq[b[j] - k]; //count++ only works when all elements are unique
  14. }
  15. if (k != 0 && freq.find(b[j] + k) != freq.end()) { // to avoid double counting when k = 0
  16. count += freq[b[j] + k];
  17. }
  18.  
  19. freq[b[j]]++;
  20. }
  21.  
  22. return count;
  23. }
  24.  
  25. int main() {
  26. vector<int> b = {1, 5, 3, 4, 2};
  27. int k = 2;
  28. cout << countPairsWithDifferenceK(b, k) << endl; // Output should be the number of pairs with difference k
  29. return 0;
  30. }
  31.  
Success #stdin #stdout 0.01s 5320KB
stdin
Standard input is empty
stdout
3