Finding duplicate values between two arrays

北慕城南 提交于 2019-11-28 10:21:19
erikreed

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!   
    }
}
Beginner

Yes, you need two loops, and yes, nested.

pseudocode it will look like:

for each in A do
    for each in B do
       if (current item of A equals to current item of B)
           say yes!
    done
done

Now everything you need is to translate it to Java. Since it sounds like a homework or some exercise you should do it by yourself.

Also, think about what output you need. If you just need a true/false whether a and b have some common values, then you can exit the loops as soon as you find the first match. If instead you need to count the number of common elements between the arrays, you'll need to throw a counter into that set of nested loops. I'll leave it up to you to figure out that portion.

You just need two nested for loops

for(int i = 0; i < a.length; i++)
{
    for(int j = 0; j < b.length; j++)
    {
        if(a[i] == b[j])
        {
            //value is in both arrays
        }
    }
}

What this does is go to the first value of a and compare to each value in b, then go to the next value of a and repeat.

Since you haven't got this tagged as homework, I'll give you the benefit of the doubt. As you said you'll need two loops; loop foreach int in a[] and foreach int in b[]. Then just compare the two values at each iteration, which gives you the simple code of:

for (int x : a) {
   for (int y : b) {
      if (x == y) {
         System.out.println("a[] and b[] both contain " + x);
      }
   }
}

Depending on the data (its size, whether every value is unique, etc) and what you're trying to get from it (ie, whether each element of a is in b, or also its index in b), it may be beneficial to do a bit of overhead work before you do the meat of it. For instance, if you sort both arrays (which you'll only need to do once), you can start the inner loop where you stopped it last (since you know that you're looking for a number >= the one you looked for last, so it's got to be at this index or greater), and you can also stop the inner loop sooner (since you know that if you're looking for X and you haven't found it before seeing a value > X, then X isn't there). Another approach would be to load both values into a Set, which you can now probe efficiently.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!