我已经阅读了一些关于这个的其他堆栈溢出线程:
to find the intersection of two multisets in java
How do I get the intersection between two arrays as a new array?
public static int[] intersection (int [] x, int numELementsInX, int [] y, int numElementsInY) {
我正在尝试检查两个数组以及它们的元素数(numElementsInX和numElementsInY),并返回一个包含数组x和y的公共值的新数组。它们的交集。
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算法。有没有人能给我举个例子说明如何做到这一点?数组和数组中的值都是在另一个方法中初始化和生成的,然后传递给交集。
任何帮助/澄清都将不胜感激。
编辑代码
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{
}
}
}
发布于 2013-07-26 00:10:41
最简单的解决方案是使用集合,只要您不关心结果中的元素将具有不同的顺序,并且重复项将被删除。输入数组array1
和array2
是给定int[]
数组的Integer[]
子数组,对应于要处理的元素数:
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[]
非常简单。
发布于 2016-06-13 19:42:58
如果您对java-8没意见,那么我能想到的最简单的解决方案就是使用streams和filter。具体实现如下:
public static int[] intersection(int[] a, int[] b) {
return Arrays.stream(a)
.distinct()
.filter(x -> Arrays.stream(b).anyMatch(y -> y == x))
.toArray();
}
发布于 2016-08-24 05:17:37
数组中有重复元素的情况下查找交集。
int [] arr1 = {1,2,2,2,2,2,2,3,6,6,6,6,6,6,};
int [] arr2 = {7,5,3,6,6,2,2,3,6,6,6,6,6,6,6,6,};
Arrays.sort(arr1);
Arrays.sort(arr2);
ArrayList result = new ArrayList<>();
int i =0 ;
int j =0;
while(i< arr1.length && j<arr2.length){
if (arr1[i]>arr2[j]){
j++;
}else if (arr1[i]<arr2[j]){
i++;
}else {
result.add(arr1[i]);
i++;
j++;
}
}
System.out.println(result);
https://stackoverflow.com/questions/17863319
复制相似问题