我知道这是一个旧线程,但没有其他答案完全解决了我的用例(我猜Guava Multiset可能做同样的事情,但这里没有例子)。请原谅我的格式。我还是一个栈交换的新手。另外,如果有任何错误,请告诉我
假设你有List<T> a和List<T> b,你想检查它们是否与以下条件相等:
1) O(n)预计运行时间
2)相等性定义为:对于a或b中的所有元素,元素在a中出现的次数等于该元素在b中出现的次数。元素相等性定义为T.equals()
private boolean listsAreEquivelent(List<? extends Object> a, List<? extends Object> b) {
if(a==null) {
if(b==null) {
//Here 2 null lists are equivelent. You may want to change this.
return true;
} else {
return false;
}
}
if(b==null) {
return false;
}
Map<Object, Integer> tempMap = new HashMap<>();
for(Object element : a) {
Integer currentCount = tempMap.get(element);
if(currentCount == null) {
tempMap.put(element, 1);
} else {
tempMap.put(element, currentCount+1);
}
}
for(Object element : b) {
Integer currentCount = tempMap.get(element);
if(currentCount == null) {
return false;
} else {
tempMap.put(element, currentCount-1);
}
}
for(Integer count : tempMap.values()) {
if(count != 0) {
return false;
}
}
return true;
}
运行时间是O(n),因为我们对hashmap进行了O(2*n)次插入和O(3*n)次hashmap选择。我还没有完全测试这段代码,所以要小心:)
//Returns true:
listsAreEquivelent(Arrays.asList("A","A","B"),Arrays.asList("B","A","A"));
listsAreEquivelent(null,null);
//Returns false:
listsAreEquivelent(Arrays.asList("A","A","B"),Arrays.asList("B","A","B"));
listsAreEquivelent(Arrays.asList("A","A","B"),Arrays.asList("A","B"));
listsAreEquivelent(Arrays.asList("A","A","B"),null);