Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting Primitive int array to list

Tags:

java

algorithm

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.

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};

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);
        }           
    }
}

And also My logic is O(n+1). Is there any better algo.

Thanks

like image 932
javaMan Avatar asked Nov 28 '22 02:11

javaMan


2 Answers

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>.

Guava has an answer to this in the Ints class. Is has an asList method that will take an int[ ] and return a List<Integer>

Update

int[] a = ...;
int[] b = ...;
List<Integer> aList = Ints.asList(a);
List<Integer> bList = Ints.asList(b);

The above will allow your code to work properly for int[ ] as it works for Integer[ ].

Check out Ints API

like image 82
John B Avatar answered Dec 11 '22 00:12

John B


Calculate the sum of each array. Sum(B) - Sum(A) will give you the extra element in B.

like image 35
rossum Avatar answered Dec 10 '22 23:12

rossum