我试图解决以下问题。有两个数组大小n和大小为n + 1的B。 A和B的所有元素相同。 B有一个额外的元素。找到的元素。
I am trying to solve the following problem. There are two arrays A of size n and B of size n+1. A and B have all elements same. B has one extra element. Find the element.
我的逻辑是将数组转换为列表并检查B中每个元素是present于A。
My logic is to convert the array to list and check if each element in B is present in A.
但是,当我使用的基本数组我的逻辑是行不通的。如果我使用
But when I am using the primitive arrays my logic is not working. If I am using
Integer [] a ={1,4,2,3,6,5};
Integer [] b = {2,4,1,3,5,6,7};
我的code是工作的罚款。
My code is working fine.
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)。有没有更好的算法中。
And also My logic is O(n+1). Is there any better algo.
感谢
推荐答案
这是不工作的基本数组的原因,就是 Arrays.asList 定当 INT [] 返回列表&LT;整数[]> 而不是一个名单,其中,整型>
The reason it is not working for primitive arrays, is that Arrays.asList when given an int[ ] returns a List<Integer[ ]> rather than a List<Integer>.
番石榴已经在
相关推荐
最新文章