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,3,4,2,4,1,1,3};
  14. int k = 2;
  15. int n = arr.length;
  16. int count=0;
  17.  
  18. HashMap<Integer,Integer> map = new HashMap<>();
  19. for(int i = 0;i<n;i++){
  20.  
  21. if(map.containsKey(Math.abs(arr[i]+k))){
  22. count += map.get(arr[i] + k);
  23. }
  24.  
  25. if(map.containsKey(Math.abs(arr[i]-k))){
  26. count += map.get(Math.abs(arr[i]-k));
  27. }
  28.  
  29. map.put(arr[i], map.getOrDefault(arr[i], 0) + 1);
  30.  
  31. }
  32. System.out.println(count);
  33. }
  34. }
Success #stdin #stdout 0.1s 54548KB
stdin
Standard input is empty
stdout
11