How to find difference between two integer arrays?

Viewed 3278

I'm trying to write a function which returns the difference between two arrays. The input arrays are not sorted. I'm assuming that that all elements in input arrays are unique. For Example:

Input: arr1 = [1,2,3,5,4] arr2 = [1,2,3]

Expected Output: [4,5]

I'm trying to implement this using an arraylist but can't find the problem with my code. Here it is:

public class Difference{
ArrayList<Integer> diff(int m[],int n[])
    {
        int mlen = m.length;
        int nlen = n.length;
        ArrayList<Integer> arr1 = new ArrayList<Integer>(Arrays.asList(m));
        ArrayList<Integer> arr2 = new ArrayList<Integer>(Arrays.asList(n));
        if(mlen>nlen)
        {
            arr1.removeAll(arr2);
            return arr1;
        }
        else
        {
            arr2.removeAll(arr1);
            return arr2;
        }

    }
    public static void main(String args[])
    {
          Difference obj = new Difference();
          int a[] = {1,2,3,4,5};
          int b[] = {1,2,3};
          System.out.println(obj.diff(a,b));
    }
}
4 Answers
Related