Given integers, count the number of pairs of integers whose difference is .
Input Format
The first line contains and .
The second line contains numbers of the set. All the numbers are unique.
The second line contains numbers of the set. All the numbers are unique.
Constraints
- Each integer will be greater than and at least smaller than .
Output Format
An integer that tells the number of pairs of integers whose difference is .
Sample Input
5 2
1 5 3 4 2
Sample Output
3
Explanation
There are 3 pairs of integers in the set with a difference of 2.
Java code:
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
static int pairs(int[] a,int k) {
/* Complete this function */
Arrays.sort(a);
int i=a.length-1;
int j=i-1,c=0;
while(j>=0)
{
if(a[i]-a[j]<k)
j--;
else if(a[i]-a[j]>k)
i--;
else if(a[i]-a[j]==k)
{
c++;
j--;
}
}
return c;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int res;
String n = in.nextLine();
String[] n_split = n.split(" ");
int _a_size = Integer.parseInt(n_split[0]);
int _k = Integer.parseInt(n_split[1]);
int[] _a = new int[_a_size];
int _a_item;
String next = in.nextLine();
String[] next_split = next.split(" ");
for(int _a_i = 0; _a_i < _a_size; _a_i++) {
_a_item = Integer.parseInt(next_split[_a_i]);
_a[_a_i] = _a_item;
}
res = pairs(_a,_k);
System.out.println(res);
}
}
Java code:
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
static int pairs(int[] a,int k) {
/* Complete this function */
Arrays.sort(a);
int i=a.length-1;
int j=i-1,c=0;
while(j>=0)
{
if(a[i]-a[j]<k)
j--;
else if(a[i]-a[j]>k)
i--;
else if(a[i]-a[j]==k)
{
c++;
j--;
}
}
return c;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int res;
String n = in.nextLine();
String[] n_split = n.split(" ");
int _a_size = Integer.parseInt(n_split[0]);
int _k = Integer.parseInt(n_split[1]);
int[] _a = new int[_a_size];
int _a_item;
String next = in.nextLine();
String[] next_split = next.split(" ");
for(int _a_i = 0; _a_i < _a_size; _a_i++) {
_a_item = Integer.parseInt(next_split[_a_i]);
_a[_a_i] = _a_item;
}
res = pairs(_a,_k);
System.out.println(res);
}
}
No comments:
Post a Comment