Java中,发现两个数组的交集 [英] Java, find intersection of two arrays

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

问题描述

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

<一个href=\"http://stackoverflow.com/questions/14610317/to-find-the-intersection-of-two-multisets-in-java\">to发现在java中 2多集的交集。

<一个href=\"http://stackoverflow.com/questions/13270491/best-way-to-find-an-intersection-between-two-arrays\">Best办法找到两个阵列之间的交集?

 公共静态INT []交集(INT [] X,INT numELementsInX,INT [] Y,诠释numElementsInY){

我想检查两个数组以及它们的元素(numElementsInX和numElementsInY)的数量,并返回包含数组x和y的共同价值的新数组。他们的交集。

 例如,如果X是{1,3,5,7,9} y是{9,3,9,4},则
相交点(X,5,Y,4}应该返回{3,9}或{9,3}

我读过我需要使用LCS算法。谁能给我一个例子就如何做到这一点?两个阵列和在数组值被初始化,并且在另一种方法产生的,然后传递到交集。

任何帮助/澄清是AP preciated。
谢谢!

编辑code ***

 的for(int i = 0; I&LT; numElementsInX;我++){
对于(INT J = 0; J&LT; numElementsInY; J ++){
如果(X [J] == X [I]){//如何推向新的数组?;
}
其他{}
}
}


解决方案

最简单的办法是使用套,只要你不关心,在结果中的元素都会有不同的秩序,而且会重复被移除。输入数组数组1 数组2 整数[] 您打算过程对应元素的数目给定的 INT [] 阵列子阵:

 设置&LT;整数GT; S1 =新的HashSet&LT;整数GT;(Arrays.asList(数组1));
SET&LT;整数GT; S2 =新的HashSet&LT;整数GT;(Arrays.asList(数组2));
s1.retainAll(S2);整数[]结果= s1.toArray(新的整数[s1.size()]);

以上将返回整数[] ,如果需要,它是简单的复制和它的内容转换成 INT []

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

to find the intersection of two multisets in java

Best way to find an intersection between two arrays?

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

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}

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.

Any help/clarification is appreciated. Thanks!

EDIT CODE***

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{

}
}
}

解决方案

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()]);

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

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

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