两个数组之间的交集

时间:2016-08-27 13:39:09

标签: java arrays intersection difference

我在查找java中两个数组之间的区别时遇到了问题,我的情况就像想象我们有两个数组一样。数组A = {1 , 3 , 5 , 7 ,9 }和数组B = {1 ,3 , 4 ,5 , 6 ,7 , 10}。我想得到两个结果第一个结果是一个数组,它从数组中找到丢失的对象" A" ,第二个结果是一个数组,它在数组" B"中找到添加的对象。第一个结果应该是A'={9},第二个结果就像B'={4,6,10}感谢您的评论。

3 个答案:

答案 0 :(得分:0)

使用此逻辑

int a1[n1],a2[n2],count1,count2,temp;

for(i=0;i<n1;i++)
{ temp=0;
  for(j=0;j<n2;j++)
   {
     if(A[i]==B[j])
      temp=1;
   }
 if(temp==0)
  {a1[count1]=A[i];
  count1++;
  }
}

for(i=0;i<n2;i++)
{ temp=0;
  for(j=0;j<n1;j++)
   {
     if(A[i]==B[j])
      temp=1;
   }
 if(temp==0)
  {a2[count2]=B[i];
  count2++;
  }
}

现在,数组a1 []包含A []但不包含在B []中的元素,而a2 []包含B []但不包含在A []中的元素。

答案 1 :(得分:0)

我认为以下代码可以帮助您

/* package whatever; // don't place package name! */

import java.util.*;
import java.lang.*;
import java.io.*;

/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{

    // your code goes here
    Map<Integer,Integer> map1=new HashMap<Integer,Integer>();
    int A[]={1 , 3 , 5 , 7 ,9 };
    int B[]={1 ,3 , 4 ,5 , 6 ,7 , 10};
    int i;
    for(i=0;i<B.length;i++)
    map1.put(B[i],1);
    for(i=0;i<A.length;i++)
    {

            Integer v1=map1.get(A[i]);
        if(v1==null)
        {

            System.out.println("Missing number="+A[i]);
        }

    }

    for(i=0;i<A.length;i++)
    {

        Integer v1=map1.get(A[i]);

        if(v1!=null)
        {int val=v1;
            map1.put(A[i],val+1);

    //      System.out.println("Missing number="+A[i]);
        }

    }
    for(i=0;i<B.length;i++)
    {
            Integer v1=map1.get(B[i]);
        if(v1!=null && v1<2)
        {

            System.out.println("Added element in B="+B[i]);
        }

    }


}
}

答案 2 :(得分:0)

使用removeAll:

    List<Integer> a = Arrays.asList(1 , 3 , 5 , 7 ,9);
    List<Integer> b = Arrays.asList(1 ,3 , 4 ,5 , 6 ,7 , 10);

    ArrayList<Integer> c = new ArrayList<>(a);
    ArrayList<Integer> d = new ArrayList<>(b);


    c.removeAll(b);
    d.removeAll(a);

    System.out.println(c);
    System.out.println(d);