通过使用递归查找数组是否对称

时间:2019-04-15 14:27:15

标签: java arrays recursion

基本上,我在大学从事递归方面的工作,但在解决此问题时遇到了问题。我必须创建两种方法,一种称为getLastElement和isSymmetric。 getLastElement只能从数组访问索引0。如果数组是对称的或为0,则isSymmetric必须显示true。 它必须使用array [0]和array.length。它也可以使用Arrays.copyOfRange()

我已经制作了isSymmetric,但是没有getLastElement,我想我缺少了一些东西,因为我不知道如何将getLastElement合并到其中。我知道我没有使用array [0],但是我无法使用代码。

这是我的代码:

public static int isSymmetric(int array[], int begin, int end) 
    { 

        if (begin >= end) { 
            return 1; 
        } 
        if (array[begin] == array[end]) { 
            return isSymmetric(array, begin + 1, end - 1); 
        } 
        else { 
            return 0; 
        } 
    } 


        public static void main (String[] args) { 
        int array[] = { 1, 2, 3, 2, 1 }; 

        if (isSymmetric(array, 0, array.length - 1) == 1) 
            System.out.print( "true"); 
        else
            System.out.println( "false"); 
        } 

我只想像现在一样打印,但是将isLymElement中包含了getLastElement。

1 个答案:

答案 0 :(得分:1)

您可以仅在这两个索引之间使用数组的副本,而不是将整个数组与索引beginend一起发送。这样做将允许您使用getLastElement函数(请参见代码)。

// I am assuming this function returns the 
// 0th-indexed element of the array.
public static int getLastElement(int[] array) {
    return array[0];    
}

public static int isSymmetric(int[] array) {
    if(array.length <= 1) return 1;

    // check if the first and the last element are equal
    if(getLastElement(array) == array[array.length -1])

        // copy the remaining array (leaving first and last element)
        return isSymmetric(Arrays.copyOfRange(array, 1, array.length-1));

    return 0;
}


public static void main (String[] args) { 
    int array[] = { 1, 2, 3, 2, 1 }; 

    if (isSymmetric(array) == 1) 
        System.out.println( "true"); 
    else
        System.out.println( "false"); 
} 

getLastElement实际上是返回数组的第一个元素,因此,如果您看到它实际上是一种getFristElement类型的函数。这样做是因为问题指出该函数只允许访问数组的0th-index。