数组求交集排序

最快速度求两个数组的交集int[] a1,int[] a2

// 排序算法
public class SortClass {

    static Map<Integer, Object> map = new ConcurrentHashMap<Integer, Object>();

    public static void main(String[] args) throws IOException {
        int[] array1 = new int[10000];
        for (int i = 0; i < 10000; i++) {
            array1[i]=i*i;
        }
        int[] array2 = new int[5000000];
        for (int i = 0; i < 5000000; i++) {
            array2[i]=i+i;
        }
        getRepeat(array1, array2);
        getRepeatfor(array1, array2);

    }

    private  static void  wirteFile() throws IOException{

        try {   
            FileOutputStream fos = new FileOutputStream (new File("d:\\a2.txt"),true ) ; 
            for (int i = 0; i < 1000; i++) {
                int k = new Random().nextInt(100000);
                 fos.write((k+",").getBytes()) ; 
            }
            fos.close ();   
        } catch (IOException e) {   
            e.printStackTrace();   
        } 

    }

    //int数组求交集-采用hash碰撞方式
    public static void getRepeat(int[] a1, int[] a2) {
        int count=0;
        long  start  = System.currentTimeMillis();
        for (int i = 0; i < a1.length; i++) {
            map.put(a1[i], a1[i]);
        }
        for (int j = 0; j < a2.length; j++) {
            if (map.get(a2[j]) != null) {
                count++;
            }
        }
        System.out.println(count);
        long  end  = System.currentTimeMillis();
        System.out.println("耗时:"+(end -start)/1000+"s");
    }

    // int数组求交集-双重for循环
    public static void getRepeatfor(int[] a1, int[] a2) {
        int count=0;
        long  start  = System.currentTimeMillis();
        for (int i = 0; i < a1.length; i++) {
            for (int j = 0; j < a2.length; j++) {
                if(a2[j]==a1[i]){
                    count++;

                }
            }
        }
        System.out.println(count);
        long  end  = System.currentTimeMillis();
        System.out.println("耗时:"+(end -start)/1000+"s");
    }
}

两个算法时间复杂度相差很大。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值