I'm not a Java expert, but one suggestion would be to subtract once in the loop:
static int pairs(int[] a, int k) {
int counter = 0;
for (int i = 0; i < a.length; i++) {
for (int j = i + 1; j < a.length; j++) {
int diff = a[i] - a[j];
if (diff == k || diff == -k) {
counter++;
}
}
}
return counter;
}
This should not hurt performance, as you already do the subtraction no less than once, and in the case of a[i]
being less than a[j]
it should help performance.
You could also precompute -k
to save on the negation of it. (Not that this is an expensive calculation.)
static int pairs(int[] a, int k) {
int counter = 0;
int negK = -k;
for (int i = 0; i < a.length; i++) {
for (int j = i + 1; j < a.length; j++) {
int diff = a[i] - a[j];
if (diff == k || diff == negK) {
counter++;
}
}
}
return counter;
}
I can't guarantee that will have performance impacts, though.
Also, another note, the for (int i : a.length)
does not appear to be valid Java.
The correct version is for (int i : a)
(according to this Oracle document), which is not actually what you are trying to do. To fix that to match with the rest of your code, you should be using for (int i = 0; i < a.length; i++)
.
Lastly (and I already did this for you) you should definitely clean up the formatting of your code. It's very hard to read as it stands. Clearing up your indentation makes the code a lot easier to follow.
for (int i : a.length )
this is a compiler error, which affects the rest of the code... \$\endgroup\$ – h.j.k. Aug 20 '15 at 15:59