首页 > 解决方案 > 使用递归查找数组是否对称

问题描述

基本上我有关于递归的大学工作,但我在解决这个问题时遇到了问题。我必须创建两种方法,一种称为 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 中。

标签: javaarraysrecursion

解决方案


您可以只在这两个索引之间使用数组的副本,begin而不是将整个数组与索引一起发送。end这样做将允许您使用您的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 个索引。


推荐阅读