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