繁体   English   中英

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

[英]Find if array is Symmetric by using 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"); 
        } 

我只想像现在一样打印,但是将getLastElement合并到isSymmetric中。

无需发送整个数组以及索引的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函数。 这样做是因为问题指出该函数仅允许访问数组的第0个索引。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM