如何通过递归函数检查并返回几个值?

时间:2013-12-12 11:36:24

标签: java algorithm recursion

我想检查第一个数组中的数字是否等于第二个数组中的任何数字,并使用递归算法返回索引的值。

public class RecursionAlgorithms1 {
    public static void main(String[] args) {
        int [] array1 = {7,1,5,10,8,4,15,60};
        int [] array2 = {1,10,8,5,15,7,60,4};
        int result[] = Check(array1, array2);
        //for (int i = 0; i < result.length; i++) {
            System.out.println(result[7]);
        //}
    }

    public static int[] Check(int [] arr1,int [] arr2){
        int index1=8;
        int index2=8;
        if (arr1[index1] != arr2[index2]) {
            return Check(arr1, arr2);
        }
        else{
            return new int [] {index1,index2};
        }
    }
}

3 个答案:

答案 0 :(得分:1)

我建议你这样写:

public class Arrays1 {
    @SuppressWarnings("empty-statement")
    public static void main(String[] args) {
        int [] array1 = {7,10,5,100,80,40,15,60};
        int [] array2 = {10,100,80,5,15,7,60,40};
        for (int i = 0; i < array1.length; i++) {
            for (int j = 0; j < array2.length; j++) {
                if (array1[i] == array2[j]) {
                   System.out.println("(" + i + "," + j + ")");
                }
            }
        }
    }
}

答案 1 :(得分:0)

递归未正确实施。在每次递归调用时,应该修改数组的索引,否则它将继续比较来自两个数组的相同元素。

答案 2 :(得分:0)

不需要递归。这将在两个数组中找到共同的元素

int [] array1 = {7,1,5,10,8,4,15,60};
int [] array2 = {1,10,8,5,15,7,60,4};
Integer[] arr=new Integer[array2.length];
for(int i=0;i<array2.length;i++){
    arr[i]=array2[i];
}


for(int i:array1){
   if(Arrays.asList(arr).contains(i)){
       System.out.println("Both arrays have "+i);
   }
}

Out put。

Both arrays have 7
Both arrays have 1
Both arrays have 5
Both arrays have 10
Both arrays have 8
Both arrays have 4
Both arrays have 15
Both arrays have 60