有两个长整型的数组A[100]和B[500],没有顺序。用最高效率的方法把两个数组中相同的数找出来,存入C[]中。
求算法?

解决方案 »

  1.   

    List list=new ArrayList();
    for(int i=0;i<A.length;i++)
    {
        for(int j=0;j<B.length;j++)
        {
            if(A[i]==B[j])
            {
                 list.add(A[i]);
            }
        }
    }Long[] C=new Long[list.size()];
    for(int i=0;i<list.size;i++)
    {
      C[i]=(Long)list.get(i);
    }
      

  2.   

    public class TestNum{


    public static Object[] getRepeatedNum(long[] l1,long[] l2){

    Set<Long> set = new HashSet<Long>();
    List<Long> list = new ArrayList<Long>();

    for(int i = 0 ; i < l1.length; i ++){
    set.add(l1[i]);
    }

    for(int i =0 ; i <l2.length;i ++){
    long lon = l2[i];
    if(set.contains(lon)){
    list.add(lon);
    }
    }


    return list.toArray();
    }


    public static void main(String[] args) {
    long[] l1 = new long[]{1,2,3,41,12};
    long[] l2 = new long[]{3,4,5,12};

    Object[] o = getRepeatedNum(l1, l2);

    for (int i = 0; i < o.length; i++) {
    System.out.println(o[i]);
    }
    }
    }
      

  3.   

    还有一个好的方法,利用Map的键不能重复性,达到存储数据。。
      

  4.   

    如果按循还次数计算,假设两个数组的长度分别为m ,n,那么1楼的是o(m*n);2楼的是o(n的平方)+o(m的平方)+(m与n中的最小值);4楼的是o(m+n);
    看上去是4楼的更快一点了