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.  
  14. int[] arr = {1, 5, 3, 4, 2};
  15. int k = 2;
  16. System.out.println(countAllPairsWithDiffK(arr,k));
  17. }
  18. static int countAllPairsWithDiffK(int[] arr, int k){
  19. HashMap<Integer,Integer> map = new HashMap<>();
  20. int cnt = 0;
  21. for(int i=0;i<arr.length;i++){
  22. if(map.containsKey(k+arr[i])){
  23. cnt+=map.get(k+arr[i]);
  24. }
  25. map.put(arr[i],map.getOrDefault(arr[i],0)+1);
  26. }
  27. return cnt;
  28. }
  29. }
Success #stdin #stdout 0.09s 54284KB
stdin
Standard input is empty
stdout
2