Code snippet ini adalah solusi yang saya tulis untuk memecahkan masalah berjudul Pairs di Hackerrank.com.
Masalah yang dihadapi bisa dilihat di sini: https://www.hackerrank.com/challenges/pairs
Problem Statement
Given N integers, count the number of pairs of integers whose difference is K.
Input Format
The first line contains N and K.
The second line contains N numbers of the set. All the N numbers are unique.
Output Format
An integer that tells the number of pairs of integers whose difference is K.
Constraints:
N≤105
0<K<109
Each integer will be greater than 0 and at least K smaller than 231−1.
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.
Solution
import java.io.*; import java.util.*; import java.text.*; import java.math.*; import java.util.regex.*; public class Solution { private static long[] sort(long[] array) { int len = array.length; for (int i=0; i<len; i++) { long buf = array[i]; for (int j=i; j>=0; j--) { if (j>0 && array[j-1] > buf) { array[j] = array[j-1]; } else { array[j] = buf; break; } } } return array; } public static void main(String[] args) { Scanner in = new Scanner(System.in); //Scanner in = new Scanner(new File("sample3.txt")); int N = in.nextInt(); long K = in.nextInt(); long[] array = new long[N]; for (int i=0; i<N; i++) { array[i] = in.nextLong(); } array = sort(array); int i = 0; int count = 0; while (i < N) { int j = i+1; while (j < N) { long diff = Math.abs(array[i] - array[j]); if ( diff == K) { count++; } if (diff > K) { break; } j++; } i++; } System.out.println(count); } }