我有两个有唯一值的排序数组(可以是ArrayLists,Collections或任何其他数据格式)。什么是比较它们的最快方法?目标是删除这两个列表中的所有值。最快的数组比较
开始:
int [] a = {1, 2, 3, 4, 5};
int [] b = {1, 2, 3, 6, 7};
末有:
a = {4, 5}
b = {6, 7}
我有两个有唯一值的排序数组(可以是ArrayLists,Collections或任何其他数据格式)。什么是比较它们的最快方法?目标是删除这两个列表中的所有值。最快的数组比较
开始:
int [] a = {1, 2, 3, 4, 5};
int [] b = {1, 2, 3, 6, 7};
末有:
a = {4, 5}
b = {6, 7}
使用合并步骤在MergeSort
List list = Arrays.asList(a);
list.retainAll(b); //now list has {1, 2, 3}
List result = Arrays.asList(a).removeAll(list); //it now has 4, 5. For b do the same
这可能是最短的代码,但它不可能是最有效的。 – jjnguy 2010-11-05 17:37:50
分析器说... ;-) – 2010-11-05 19:01:32
您可以轻松地为O比较(n)的最坏情况 – Andrey 2010-11-05 17:25:48