Java,找到两个数组的交集 [英] Java, find intersection of two arrays

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

问题描述

我已经阅读了其他一些关于此的堆栈溢出线程:

I have already read a few other stack overflow threads on this:

在java中求两个多重集的交集

如何获得两个数组之间的交集作为新数组?

public static int[] intersection (int [] x, int numELementsInX, int [] y, int numElementsInY) {

我试图检查两个数组以及它们的元素数量(numElementsInX 和 numElementsInY),并返回一个包含数组 x 和 y 的公共值的新数组.他们的交集.

I am trying to examine two arrays as well as their number of elements (numElementsInX and numElementsInY), and return a new array which contains the common values of array x and y. Their intersection.

Example,if x is{1,3,5,7,9}and y is{9,3,9,4} then
intersection(x, 5, y, 4} should return {3, 9} or {9, 3}

我读过我需要使用 LCS 算法.谁能给我一个例子来说明如何做到这一点?数组和数组中的值都在另一个方法中初始化和生成,然后传递到交集.

I've read I need to use the LCS algorithm. Can anyone give me an example as to how to do this? Both the array and values in array are initialized and generated in another method, then passed into intersection.

感谢任何帮助/澄清.

编辑代码

for (int i=0; i<numElementsInX; i++){
    for (int j=0; j<numElementsInY; j++){
        if (x[j]==x[i]) { //how to push to new array?; 
        }
        else{
        }
    }
}

推荐答案

最简单的解决方案是使用集合,只要你不关心结果中的元素会有不同的顺序,重复的会被移除.输入数组 array1array2 是给定 int[] 数组的 Integer[] 子数组,对应于您打算处理的元素数量:

The simplest solution would be to use sets, as long as you don't care that the elements in the result will have a different order, and that duplicates will be removed. The input arrays array1 and array2 are the Integer[] subarrays of the given int[] arrays corresponding to the number of elements that you intend to process:

Set<Integer> s1 = new HashSet<Integer>(Arrays.asList(array1));
Set<Integer> s2 = new HashSet<Integer>(Arrays.asList(array2));
s1.retainAll(s2);

Integer[] result = s1.toArray(new Integer[s1.size()]);

以上将返回一个 Integer[],如果需要,可以简单地将其内容复制并转换为 int[].

The above will return an Integer[], if needed it's simple to copy and convert its contents into an int[].

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

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