[英]Common elements of muiltiple arrays but not using Lists
有没有办法我可以在数组中返回2个或更多数组的公共元素? 我知道在列表下有一些方法可以做到,但是有没有办法只使用数组呢? 因为创建了一个名为OrderedIntList的数组,所以我做了自己的get和length btw。
例如:
1,3,5
1,6,7,9,3
1,3,10,11
结果:1,3
我试过了,它输出两个数组之间的公共元素,而不是全部。 我知道有什么问题,但是我不知道如何使它正常工作:(
//返回输入数组的公共元素
public static OrderedIntList common(OrderedIntList ... lists){
int[] list = new int[10];
for(int x = 1; x <= lists.length -1; x++){
for(int q = 0; q < lists[0].length()-1; q++) {
for(int z = 0; z < lists[x].length(); z++) {
if (lists[0].get(q)==lists[x].get(z)){
list[q] = lists[0].get(q);
}
}
}
}
OrderedIntList newlist = new OrderedIntList(list);
return newlist;
}
您可以使用
org.apache.commons.collections.CollectionUtils.intersection(java.util.Collection a, java.util.Collection b)
获取两个列表的交集(两个列表中都存在元素)
并将您的数组作为Collection传递:java.util.Arrays.asList(Object [] a);
但是,充其量来说,处理数组很乏味。 您应该考虑为什么不想使用收藏夹...
这可能是解决问题的简单算法...
1) Instantiate an instance variable of type array called "commonElements" pointing to the elements of the first Array. At the beginning these are your common elements. 2) Create a method call getCommonElements(int[] commonElements, int[] newList). This method manipulates the commonElements array to leave it with only the common elements between the two. (ps Use a temporary array to achieve this if you find it easier) 3) Iterate over all the arrays present in "lists" starting from the second array. 4) call the method at point 2 for each array .
对您而言,所有困难的部分是实现一种方法,该方法使给定的2个数组查找公共元素!
作为部分回答,您可能会通过完全重新实现OrderedIntList的方式来做很多工作,因为ArrayList和朋友已经通过Collections类进行了排序。
import java.util.Collections;
public class OrderedIntList extends ArrayList<Integer> {
@override // to effect sorted inserts
public void add(Integer i) {
this.add(i);
Collections.sort(this);
// done.
}
}
希望对纯数组执行此操作是一个不错的练习,但是这样做会更好,您可以使用快速排序(无法在没有获得一百万个结果的情况下通过网络搜索该Java实现的网络搜索)或插入排序(同样可通过网络搜索),并遵循相同的食谱。
每当您将数字推入数组时:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.