发现两个阵列之间的重复值 [英] Finding duplicate values between two arrays

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

问题描述

比方说,我有以下两个数组:

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 。所以,我会得到从'1' A 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)的时间。你应该利用一个HashMap / HashSet的一个显着更快的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天全站免登陆