java - 使用递归查找数组是否对称
问题描述
基本上我有关于递归的大学工作,但我在解决这个问题时遇到了问题。我必须创建两种方法,一种称为 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 中。
解决方案
您可以只在这两个索引之间使用数组的副本,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 个索引。
推荐阅读
- c - 使用函数时无法获得小数?
- marklogic - RHEL MarkLogic 9.0-6.2 不包括 Schematron?
- google-app-engine - 将数据文件上传到我的 Google 应用引擎应用
- python - Gunicorn StatsD 指标
- visual-studio - 如何在 iOS 上部署 apache cordova 应用程序?
- operating-system - “64位操作系统”、“基于x64的处理器”与字长有什么关系?
- ios - visual studio 2017(windows)不显示来自mac的所有可用ios模拟器设备
- javascript - 无法修复关于在 switch 语句中缩进 case 语句的 eslint 规则
- abap - 如何从组件控制器调用弹出窗口并在 WDA 中处理 subscribe_to_button_event
- networking - 如何接收发送到 ff:ff:ff:ff:ff:ff 的数据包