我想寫一個函數,它返回兩個數組之間的差異。 輸入數組未被排序。我假設輸入數組中的所有元素都是唯一的。 例如:如何找到兩個整數數組之間的區別?
輸入:arr1 = [1,2,3,5,4]
arr2 = [1,2,3]
預期輸出:[4,5]
我想實現這個使用一個ArrayList,但無法找到我的代碼的問題。 這就是:
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));
}
}
命令是否重要? –
您是否嘗試過調試您的應用程序? – f1sh
@JeanLogeart你是指輸出中的順序嗎? – coder7777