初学者递归问题求解
存在两个数组 int[] a1 = {2, 6, 6, 7, 8, 19, 23, 35, 53};int[] a2 = {2, 6, 7, 9, 17, 21, 35, 53};
现在希望不用循环,用递归算法找出相同元素,通过System.out.println(Arrays.toString(ArrayIntersect.arrayIntersection(a1, a2)));
希望输出 [2, 6, 6, 7, 35, 53]
public class ArrayIntersect {
public static int[] arrayIntersection(int[] a, int[] b) {
int[] c = new int[0];
int i=a.length;
if(a[0]==b[0]&&i>0){
int[] temp = Arrays.copyOf(c, c.length + 1);
temp[c.length] = a[0];
c = temp;
a=Arrays.copyOfRange(a, 1, a.length);
return arrayIntersection(a,b);
}else if(a[0]!=b[0]&&i>0){
boolean t;
t=arrayb(a[0],b);
if(t=true){
a=Arrays.copyOfRange(a, 1, a.length);
int[] temp = Arrays.copyOf(c, c.length + 1);
temp[c.length] = a[0];
c = temp;
return arrayIntersection(a,b);
}else{
a=Arrays.copyOfRange(a, 1, a.length);
return arrayIntersection(a,b);
}
}else{
return c;
}
}
public static boolean arrayb(int a,int[]b){
if(b.length>0){
if(a!=b[0]){
b=Arrays.copyOfRange(b, 1, b.length);
return arrayb(a,b);
}else{
return true;
}
}else{
return false;
}
}
}
思路是希望通过每次复制缩短a数组,用a[0]和b数组进行比较,但应该如何处理b数组,应该如何修改上面错误的代码,或者说有没有新的利用递归方法解此题的思路,求指导,谢谢!!!