fork download
  1. import java.util.*;
  2.  
  3. public class Main {
  4. static int countPairsWithSum(int[] b, int k) {
  5. int count = 0;
  6. Map<Integer, Integer> seen = new HashMap<>();
  7.  
  8. for (int j = 0; j < b.length; ++j) {
  9. int complement = k - b[j];
  10. if (seen.containsKey(complement)) {
  11. count++;
  12. }
  13. seen.put(b[j], j);
  14. }
  15.  
  16. return count;
  17. }
  18.  
  19. public static void main(String[] args) {
  20. int[] b = {1, 2, 3, 4, 5};
  21. int k = 6;
  22. int count = countPairsWithSum(b, k);
  23.  
  24. System.out.println("Count of pairs with sum " + k + " is: " + count);
  25. }
  26. }
Success #stdin #stdout 0.18s 57428KB
stdin
Standard input is empty
stdout
Count of pairs with sum 6 is: 2