Skip to content

Instantly share code, notes, and snippets.

@jinahya
Last active April 6, 2019 10:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jinahya/96dd33ece319d4393c1eb3b05cfefd3c to your computer and use it in GitHub Desktop.
Save jinahya/96dd33ece319d4393c1eb3b05cfefd3c to your computer and use it in GitHub Desktop.
Cracking the Coding Interview
import java.util.*;
class CountPairsOfIntegersThatHaveDifferenceK {
static int f1(/*distinct*/final int[] A, final int K) {
int count = 0;
for (int i = 0; i < A.length - 1; i++) {
for (int j = i + 1; j < A.length; j++) {
if (Math.abs(A[j] - A[i]) == K) {
count++;
}
}
}
return count;
}
static int f2(final int[] A, final int K) {
final Set<Integer> set = new HashSet<>();
for (final int a : A) {
set.add(a);
}
int count = 0;
for (final int a: A) {
if (set.contains(a + K)) {
count++;
}
}
return count;
}
public static void main(final String... args) {
if (args.length < 3) {
return;
}
final int[] A = new int[args.length - 1];
for (int i = 0; i < A.length; i++) {
A[i] = Integer.parseInt(args[i]);
}
final int K = Integer.parseInt(args[args.length - 1]);
System.out.println(f1(A, K));
System.out.println(f2(A, K));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment