Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find common elements in two unsorted array

Tags:

java

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!

like image 364
user1841492 Avatar asked Aug 27 '13 22:08

user1841492


People also ask

How do you find the common elements in three unsorted arrays?

A simple solution is to first find intersection of two arrays and store the intersection in a temporary array, then find the intersection of third array and temporary array. Time complexity of this solution is O(n1 + n2 + n3) where n1, n2 and n3 are sizes of ar1[], ar2[] and ar3[] respectively.


1 Answers

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")

like image 171
SJuan76 Avatar answered Oct 13 '22 22:10

SJuan76