1.4.12 有序的打印两个有序数组的公共元素
2016-07-28 本文已影响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);
}