Created
February 24, 2019 15:23
-
-
Save bingli224/d7532d9efcc4dd36fd1c63c20bdd8ab3 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.*; | |
import java.math.*; | |
import java.security.*; | |
import java.text.*; | |
import java.util.*; | |
import java.util.concurrent.*; | |
import java.util.regex.*; | |
public class Solution { | |
// Complete the pairs function below. | |
static int pairs(int k, int[] arr) { | |
// 22:23 THA 24/02/2019 | |
// by BingLi224 | |
// Reference: https://www.hackerrank.com/challenges/pairs/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=search | |
// sort the array first | |
Arrays.parallelSort ( arr ); | |
int l = 0; | |
int r = 1; | |
int sz = arr.length; | |
int maxL = sz - 1; | |
int pair = 0; | |
int total = 0; | |
while ( l < maxL ) { | |
pair = arr [ l ] + k; | |
// find pair | |
while ( r < sz && pair > arr [ r ] ) { | |
r ++; | |
} | |
if ( r >= sz ) | |
break; | |
if ( arr [ r ] == pair ) { | |
// found pair | |
total ++; | |
r ++; | |
} | |
// find next | |
l ++; | |
} | |
return total; | |
} | |
private static final Scanner scanner = new Scanner(System.in); | |
public static void main(String[] args) throws IOException { | |
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH"))); | |
String[] nk = scanner.nextLine().split(" "); | |
int n = Integer.parseInt(nk[0]); | |
int k = Integer.parseInt(nk[1]); | |
int[] arr = new int[n]; | |
String[] arrItems = scanner.nextLine().split(" "); | |
scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?"); | |
for (int i = 0; i < n; i++) { | |
int arrItem = Integer.parseInt(arrItems[i]); | |
arr[i] = arrItem; | |
} | |
int result = pairs(k, arr); | |
bufferedWriter.write(String.valueOf(result)); | |
bufferedWriter.newLine(); | |
bufferedWriter.close(); | |
scanner.close(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment