I'm trying to solve an algorithm problem, but I think my resolution is not good in performance. So if someone could help I will be very grateful.
The problem is: I have 3 arrays A,B,C. I want to know how many elements are within range of each B[i] and C[i].
Example:
A = [1,3,5,8]
B = [3,8]
C= [7,8]
So for B[0] and C[0] the answer is 2, because 3 and 5 are within range
and for B[1] and C[1] the answer is 1, because 8 are within range
the result has to be an array of [2,1].
Specifications:
B.length == C.length
B[i] <= C[i]
I tried my to solve this problem that way:
static int[] method(int[] A, int[] B, int[] C) {
Arrays.sort(A);
int[] result = new int[B.length];
for (int i = 0; i < B.length; i++) {
int x = B[i];
int y = C[i];
int init = -1;
int end = -1;
for (int j = 0; j < A.length; j++) {
int a = A[j];
if (a >= x && init == -1) {
init = j;
}
if (a == y && end == -1) {
end = j;
}
if (a > y && end == -1) {
end = j - 1;
}
if (init != -1 && end != -1) {
break;
}
}
result[i] = end - init + 1;
}
return result;
}
What do you guys think?