fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. /* Name of the class has to be "Main" only if the class is public. */
  8. class Ideone
  9. {
  10. public static void main (String[] args) throws java.lang.Exception
  11. {
  12. // your code goes here
  13. int[] arr = {1, 7, 5, 9, 2, 12, 3};
  14. int k = 2;
  15. System.out.println(countPairsWithAbsoluteDiffK(arr,k));
  16.  
  17. }
  18.  
  19. static int countPairsWithAbsoluteDiffK(int[] arr, int k){
  20. HashMap<Integer,Integer> map = new HashMap<>();
  21. int cnt = 0;
  22. for(int i=0;i<arr.length;i++){
  23. int req1 = arr[i]+k;
  24. int req2 = arr[i]-k;
  25. if(map.containsKey(req1)){
  26. cnt+=map.get(req1);
  27. }
  28. if(k!=0 && map.containsKey(req2)){
  29. cnt+=map.get(req2);
  30. }
  31. map.put(arr[i],map.getOrDefault(arr[i],0)+1);
  32. }
  33.  
  34. return cnt;
  35. }
  36. }
Success #stdin #stdout 0.09s 52528KB
stdin
Standard input is empty
stdout
4