两个有序(从小到大且不重复)的超大型数组,求其交集算法实现

题目说明:

两个超大型整形数组,两个数组中的数据顺序都是是从小到大排列且不重复,使用算法来实现求两个数组的交集。

代码实现:

package com.jintao.example.algorithm;

import org.junit.Test;

import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: jinjueYang
 * Date: 2019/9/2
 * Time: 8:52
 * Description:两个有序(从小到大且不重复)的超大型数组,求其交集
 */
public class SortArrayIntersection {
    public static void main(String[] args) {
        int array1[] = new int[]{1, 5, 54, 543, 5423, 5455, 6000, 7000, 8000, 9000, 10000};
        int array2[] = new int[]{1, 6, 64, 543, 6000, 7000, 9000};
        int array1Len = array1.length;
        int array2Len = array2.length;
        List<Integer> intersectionList = new ArrayList<>();
        int q = 0;
        outerLoop:
        for (int p = 0; p < array1Len; p++) {
            if (q >= array2Len) {
                System.out.println("break!!!");
                break;
            }
            for (; q < array2Len; q++) {
                int value1 = array1[p];
                int value2 = array2[q];
                if (value1 == value2) {
                    //交集
                    intersectionList.add(value1);
                    q++;
                    continue outerLoop;
                } else if (value1 > value2) {
                    continue;
                } else {
                    continue outerLoop;
                }
            }
        }

        System.out.println(intersectionList.size());
    }

    @Test
    public void Test() {
        int arr1[] = new int[]{1, 5, 54, 543, 5423, 5455, 6000, 7000, 8001, 9000, 10000};
        int arr2[] = new int[]{1, 6, 64, 543, 6000, 7000, 9000};
        List<Integer> intersectionList = new ArrayList<>();
        int p1 = 0;
        int p2 = 0;
        while (p1 < arr1.length && p2 < arr2.length) {
            if (arr1[p1] == arr2[p2]) {
                intersectionList.add(arr1[p1]);
                p1++;
                p2++;
            } else if (arr1[p1] < arr2[p2]) {
                p1++;
            } else {
                p2++;
            }
        }
        System.out.println(intersectionList.size());
    }
}

代码说明:

上述代码使用了两种方式实现,main方法里面使用的是for循环的形式,Test方法里面使用的是while循环的形式,其基本思想都是一样的,首先声明两个变量p,q,分别指向两个数组的下标,如果该下标指向的两个值相等则表示是交集,则执行p++,q++,然后加入交集List中,如果是不等,则分别判断大于还是小于,然后执行,p++或q++,继续循环比较,直到其中一个数组被遍历完毕则结束。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值