gpt4 book ai didi

java - Java 中数组传递给函数时的有趣之处

转载 作者:行者123 更新时间:2023-12-01 12:16:04 25 4
gpt4 key购买 nike

当我在 Java 中将数组作为函数参数传递时,请说:

public static void main(String... args){
int[] in=new int[]{57,40...23};
int[] post=new int[]{50,18...0};//arrays abbreviated for expediency
treeNode tree=buildTree(in, post);
print(tree);
}

public static treeNode buildTree(int[] in, int[] post)
{
int root_data= post[(post.length)-1];
int root_index=search(root_data, in);
treeNode root=new treeNode(root_data);
root.setLeft(buildTree(subArray(in, 0, root_index),subArray(post, 0, root_index)));
root.setRight(buildTree(subArray(in,root_index+1, in.length),
subArray(post,root_index, post.length-1)));
return root;
}

public static int[] subArray(int[] array, int start, int end)
{
int[] result=new int[end-start];
for(int i=0; i<end-start;i++)
{
result[i]=array[start+i];
}
return result;
}

public static int search(int key, int[] array)
{
for(int i=0; i<array.length; i++){
if(array[i]==key)
return key;
}
return array.length;
}

我收到 arrayIndexOutOfBounds 异常。通过调试器我发现数组的长度神秘地变成了0。这是为什么?

最佳答案

在您的 search() 方法中,您可能希望返回 i 而不是 key。由于您稍后使用 root_index 变量(通过此函数找到的)作为数组索引,因此您可能会遇到麻烦(抛出 arrayIndexOutOfBounds 异常)。即使 root_index 在数组索引范围内,它的值仍然是错误的 - 准确地说,在您的示例中它是 0 ,而 subArray() 方法返回空数组。

您可能需要考虑使用标准工具而不是您自己的方法:

  • Arrays.sort() 后跟 Arrays.binarySearch() 进行搜索:尽管渐进地它比简单搜索更糟糕 - O(n*lon(n) )排序加上 O(log(n)) 到二分搜索与 O(n) 在你的情况下 - 考虑到你可能有小数组,这仍然是合理的,但你得到了算法的保证正确性
  • Arrays.copyOfRange() 复制数组范围

此外,我没有看到 treeNode 类的任何定义,但我猜您只是为了简洁而在发布的代码片段中省略了它。

关于样式的快速说明:在 Java 中,使用驼峰命名法调用变量和方法(因此您可能需要将 root_index 重命名为 rootIndex 等)类以大写字母开头(因此 treeNode 最好命名为 TreeNode)。这将使其他人在阅读您的代码时更(直观)地理解您的代码。

希望有帮助!

关于java - Java 中数组传递给函数时的有趣之处,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27008740/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com