查找两个数组之间的重复值 [英] Finding duplicate values between two arrays

查看:26
本文介绍了查找两个数组之间的重复值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下两个数组:

Let's say I have the following two arrays:

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

我想取数组 a 的第一个值 - 1 - 看看它是否包含在数组 b 中.所以,我会得到 a 中的1"在 b 中,即使它不在同一位置.完成对 a 中第一个元素的比较后,我将继续处理数组 a 中的下一个数字并继续该过程,直到我完全通过第一个元素数组.

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.

我知道我需要做一些循环(可能是嵌套的?)但我无法弄清楚如何在循环数组中的所有数字时只使用数组 a 中的第一个数字b.

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...

推荐答案

这些解决方案都需要 O(n^2) 的时间.您应该利用哈希图/哈希集来获得更快的 O(n) 解决方案:

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

这篇关于查找两个数组之间的重复值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆