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. Scanner sc = new Scanner(System.in);
  13. int size = sc.nextInt();
  14.  
  15. int[] arr =new int[size];
  16.  
  17. int target = sc.nextInt();
  18.  
  19. for(int i = 0;i<size;i++){
  20. arr[i] = sc.nextInt();
  21. }
  22.  
  23.  
  24.  
  25. int result = countPairs(arr,target);
  26. System.out.println(result);
  27.  
  28. }
  29.  
  30. public static int countPairs(int arr[], int target) {
  31. // code here
  32. Map<Integer,Integer> map = new HashMap<>();
  33.  
  34. int count = 0;
  35. for(int num : arr){
  36.  
  37. int complement = target - num;
  38.  
  39. if(map.containsKey(complement)){
  40.  
  41. count+=map.get(complement);
  42.  
  43. }
  44. map.put(num,map.getOrDefault(num,0)+1);
  45. }
  46.  
  47. return count;
  48.  
  49. }
  50.  
  51. }
Success #stdin #stdout 0.11s 54484KB
stdin
5
4
2 2 1 3 1
 
stdout
3