Link: Pairs
This is the deformation of the two sum problem! The two sum problem requires that the two numbers in the array and the number is exactly equal to K. This is to find that the difference between the two numbers in the array is exactly equal to the two numbers in K. The conclusion is actually the question of "riding a donkey to find a horse": traversing ar [I], you only need to check whether ar [I] + K or AR [I]-K exists in the array, or use hashmap to complete this operation at O (1) time.
The question is not clear about whether the elements are repeated. It seems that there are no duplicates from editorial, but I still use the value of map to record the occurrence frequency of the number to process the duplicates.
The Code is as follows:
1 import java.util.*; 2 3 public class Solution { 4 public static void main(String[] args) { 5 Scanner in = new Scanner(System.in); 6 int n = in.nextInt(); 7 int k = in.nextInt(); 8 HashMap<Integer, Integer> map = new HashMap<Integer,Integer>(); 9 int[] ar = new int[n];10 for(int i = 0;i < n;i ++){11 ar[i] = in.nextInt();12 if(!map.containsKey(ar[i]))13 map.put(ar[i], 0);14 map.put(ar[i], map.get(ar[i])+1);15 }16 17 int answer = 0;18 for(int i = 0;i < n;i ++){19 int up = ar[i]+k;20 if(map.containsKey(up))21 answer += map.get(up);22 int down = ar[i]-k;23 if(map.containsKey(down))24 answer += map.get(down);25 }26 System.out.println(answer/2);27 28 }29 }