Last active
April 6, 2019 10:11
-
-
Save jinahya/96dd33ece319d4393c1eb3b05cfefd3c to your computer and use it in GitHub Desktop.
Cracking the Coding Interview
This file contains 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.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