繁体   English   中英

如何找到两个整数数组之间的差异?

[英]How to find difference between two integer arrays?

我正在尝试编写一个函数,该函数返回两个数组之间的差。 输入数组未排序。 我假设输入数组中的所有元素都是唯一的。 例如:

输入: 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));
    }
}

代码的问题是,您试图对ArrayList(int[] numbers)使用不存在的构造函数,您必须将mn中的每个数字都添加到ArrayList或者使用双括号初始化,例如

ArrayList < Integer > arr1 = new ArrayList < Integer > () {
    {
        for (int i: m) add(i);
    }
}
ArrayList < Integer > arr2 = new ArrayList < Integer > () {
    {
        for (int i: n) add(i);
    }
}

在一行中,它看起来像没有格式化

new ArrayList<Integer>() {{for(int i:m) add(i);}};

另一种优选的方式是在迭代时添加每个数字,例如

 ArrayList<Integer> arr1 = new ArrayList<Integer>();
 for(int i: m) arr1.add(i);

您的代码可以编译吗?

就像其他人建议的那样,您的ArrayList是Integer类型,而不是int类型。 这是一个编辑:

public static void main(String args[])
{
      Difference obj = new Difference();
      int a[] = {1,2,3,4,5};
      int b[] = {1,2,3};
      Integer[] anew = Arrays.stream(a).boxed().toArray( Integer[]::new );
      Integer[] bnew = Arrays.stream(b).boxed().toArray( Integer[]::new );
      System.out.println(obj.diff(anew,bnew));
}

最后,如果您确实使用了此功能,请记住将diff的参数更改为Integer类型。

最简单的解决方案是通过jQuery

function array_diff(array1, array2){
  var diff = $(array1).not(array2).get();
  return diff;
}

console.log(array_diff([1,2,3,4,5,6], [1,2,3,4]));

万一有人最终遇到这个问题,请在标题中寻找问题的答案。 这是一种实现方法:

int a[] = {1,2,3,4,5};
int b[] = {1,2,3,6};

int[] uniqueEntries = IntStream.concat(IntStream.of(a), IntStream.of(b))
    .filter(x -> !IntStream.of(a).anyMatch(y -> y == x) || !IntStream.of(b).anyMatch(z -> z == x))
    .toArray();

System.out.println(Arrays.toString(uniqueEntries));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM