【问题标题】:Find if array is Symmetric by using recursion使用递归查找数组是否对称
【发布时间】:2019-04-15 14:27:15
【问题描述】:

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

【问题讨论】:

  • 你能解释一下你的getLastElement函数吗?
  • 它说它仅限于访问索引 0 元素。这是我老师给我的pdf上唯一写的东西。对不起,如果您看不懂,我是用我的语言翻译的,它可能失去了一些意义。
  • 我认为问你这个问题的人希望你在函数isSymmetric() 中创建一个新数组,其中包含输入数组的所有元素,除了第一个和最后一个元素。虽然你正在做的是传递整个数组,并告诉函数从哪里开始和在哪里结束。

标签: java arrays recursion


【解决方案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 类型的函数。这样做是因为问题指出该函数只允许访问数组的第 0 个索引。

【讨论】:

  • 还有一件事。我将如何去打印这个?它给了我一个错误。抱歉打扰了,我只是累了。
  • 你想打印什么?
  • 如果是对称打印为真。如果不是 print false。
  • 我已经更新了答案,希望对您有所帮助。我认为您可能向 isSymmetric 函数发送了额外的参数。
  • 刚刚看到编辑。非常感谢您的回答。祝你有美好的一天!
猜你喜欢
  • 2021-03-17
  • 2021-04-15
  • 2012-08-22
  • 2021-11-19
  • 2015-06-11
  • 2019-03-11
  • 1970-01-01
  • 2014-03-26
  • 2012-11-30
相关资源
最近更新 更多