我有两个arraylists,我正在寻找一种有效的方法来计算不同值的数量。
一些示例列表:
List<String> list = new ArrayList<String>();
list.add("String A");
list.add("String B");
list.add("String C");
List<String> anotherlist = new ArrayList<String>();
list.add("String B");
list.add("String A");
list.add("String D");
你可以做一些事情来检查每个项目(因为顺序无关紧要),如果它是相同或不同(纯概念):
for(int i=0;i<list.size();i++)
{
for(int j=0;j<anotherlist.size();j++)
{
if (item.get(i) == item.get(j)){
intDifferent = intDifferent+1;
} else {
intSame = intSame+1;
}
intTotal = intTotal+1
}
}
//Some calculations with intdifferent en inttotal to find out how many different
//values we actually have between the lists, in the case of the example, it
//should output 1
有更有效的方法吗?或者是否有关于如何实现此目的的样本或帖子?
答案 0 :(得分:0)
您应该考虑使用Set
来实现此目的。
将所有项目从一个数组中删除到HashSet
,然后循环遍历另一个数组,检查它是否包含在Set
中。
这比每次循环ArrayList
要快得多。
答案 1 :(得分:0)
以下算法最坏情况复杂度为O(n * log(n))
// worst case O(nLog(n))
Collections.sort(l1);
// worst case O(nLog(n))
Collections.sort(l2);
// pointer for l1 list
int p = 0;
// pointer for l2 list
int q = 0;
int diffCounter = 0;
// worst case N
while (true) {
if (p == l1.size() -1 ) {
// remainig items in l2 list are diff
diffCounter += (l2.size() -1) - q;
break;
}
if (q == l2.size() -1 ) {
diffCounter += (l1.size() - 1) - p;
}
int compareResult = l1.get(p).compareTo(l2.get(q));
if (compareResult > 0) {
p++;
diffCounter++;
} else if (compareResult < 0 ) {
q++;
diffCounter++;
}
`