【发布时间】:2011-09-23 14:35:34
【问题描述】:
我正在尝试解决以下问题。有两个大小为 n 的数组 A 和大小为 n+1 的 B。 A 和 B 的所有元素都相同。 B 有一个额外的元素。找到元素。
我的逻辑是将数组转换为列表并检查 B 中的每个元素是否存在于 A 中。
但是当我使用原始数组时,我的逻辑不起作用。如果我正在使用
Integer [] a ={1,4,2,3,6,5};
Integer [] b = {2,4,1,3,5,6,7};
我的代码运行良好。
public static void main(String [] args)
{
int [] a ={1,4,2,3,6,5};
int [] b = {2,4,1,3,5,6,7};
List<Integer> l1 = new ArrayList(Arrays.asList(a));
List<Integer> l2 = new ArrayList(Arrays.asList(b));
for(Integer i :l2)
{
if(!l1.contains(i))
{
System.out.println(i);
}
}
}
而且我的逻辑是 O(n+1)。有没有更好的算法。
谢谢
【问题讨论】:
-
您的逻辑是 n*m,基本上是平方 (n^2),因为对于您在第二个数组中搜索的数组的每个元素,在字典/地图搜索的情况下它会更快,但在您的列表的情况是 n^2