美文网首页
1.4.12 有序的打印两个有序数组的公共元素

1.4.12 有序的打印两个有序数组的公共元素

作者: 风亡小窝 | 来源:发表于2016-07-28 15:15 被阅读11次
public static int[] intersect(int[] a, int[] b){
    int posa = 0;
    int posb = 0;
    int lena = a.length;
    int lenb = b.length;
    
    int len = lena < lenb ? lena : lenb;
    int[] al = new int[len];
    int posal = 0;
    
    while(posa < lena && posb < lenb){
        if(a[posa] > b[posb]) {
            posb++;
        }else if(a[posa] < b[posb]){
            posa++;
        }else{
            al[posal++] = a[posa];
            posa++;
            posb++;
        }
    }
    
    return Arrays.copyOfRange(al, 0, posal);
}

相关文章

网友评论

      本文标题:1.4.12 有序的打印两个有序数组的公共元素

      本文链接:https://www.haomeiwen.com/subject/diuajttx.html