Find common elements in two unsorted array

java

Solution

Given your explanation, I think the most direct approach is reading array A, putting all elements in a `Set` (setA), do the same with B (setB), and use the `retainAll` method to find the intersection of both sets (items that belong to both of the sets).

You will see that the `k distance` is not used at all, but I see no way to use that condition that leads to code either faster or more maintenable. The solution I advocate works without enforcing that condition, so it works also when the condition is true (that is called "weakening the preconditions")

Problem

I try to find a solution to this problem: I have two arrays A and B of integers (A and B can have different dimensions). I have to find the common elements in these two arrays. I have another condition: the maximum distance between the common elements is k. So, this is my solution. I think is correct: ``` for (int i = 0; i<A.length; i++){ for (int j=jlimit; (j<B.length) && (j <= ks); j++){ if(A[i]==B[j]){ System.out.println(B[j]); jlimit = j; ks = j+k; }//end if } } ``` Is there a way to make a better solution? Any suggestions? Thanks in advance!

Original source