Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding duplicate values between two arrays

Let's say I have the following two arrays:

int[] a = [1,2,3,4,5];
int[] b = [8,1,3,9,4];

I would like to take the first value of array a - 1 - and see if it is contained in array b. So, I would get that the '1' from a is in b even if it is not in the same position. Once I have gone through the comparison for the first element in a, I move on to the next number in array a and continue the process until I have completely gone through the first array.

I know I need to do some looping (possibly nested?) but I can't quite figure out how I stick with just the first number in array a while looping through all the numbers in array b.

This seems to be fairly simple I just can't get my head around it...

like image 936
user1076802 Avatar asked Dec 04 '11 23:12

user1076802


1 Answers

These solutions all take O(n^2) time. You should leverage a hashmap/hashset for a substantially faster O(n) solution:

void findDupes(int[] a, int[] b) {
    HashSet<Integer> map = new HashSet<Integer>();
    for (int i : a)
        map.add(i);
    for (int i : b) {
        if (map.contains(i))
            // found duplicate!   
    }
}
like image 92
erikreed Avatar answered Nov 07 '22 07:11

erikreed