递归构建数组遇栈溢出求助:需符合指定compare方法签名
问题分析与修复方案
栈溢出的直接原因
你递归调用里用了 index++,这是后自增运算符——它会先把当前的index值传递给递归方法,再对index加1。这导致每次递归的index永远是初始的0,永远触发不了index >= comparedArray.length的终止条件,无限递归下去,最终栈溢出。
把index++改成index + 1(或者++index,但index + 1无副作用更稳妥),就能让索引正常递增,递归正常终止。
符合题目要求的方法签名调整
题目要求的方法签名是public static int[] compare(int[] left, int[] right);,你当前代码里的compare是带四个参数的重载,不符合要求。可以把带参数的递归方法改成私有辅助方法,用题目要求的public方法作为入口:
- 在public方法里先创建结果数组(长度和输入数组一致,若不同可以取较短的长度);
- 调用私有递归辅助方法填充数组;
- 返回结果数组。
修正后的完整代码
public class RecursiveMethod { public static void main(String[] args) { int[] left = {1, 2, 4, 8, 11}; int[] right = {1, 3, 2, 9, 10}; int[] comparedArray = compare(left, right); for(int i : comparedArray) { System.out.print(i + " "); } } // 题目要求的方法签名 public static int[] compare(int[] left, int[] right) { // 假设两个数组长度相同,若不同可以取Math.min(left.length, right.length) int[] result = new int[left.length]; return compareHelper(left, right, result, 0); } // 私有递归辅助方法 private static int[] compareHelper(int[] left, int[] right, int[] comparedArray, int index) { if(index >= comparedArray.length) { return comparedArray; } int greater = 0; if(left[index] > right[index]) { greater = left[index]; } else if(left[index] < right[index]) { greater = right[index]; } // 这里可以优化:如果相等的情况,当前代码赋值0,若需要取相等的值可以改成greater = left[index] comparedArray[index] = greater; // 用index + 1传递递增后的索引,避免后自增的坑 return compareHelper(left, right, comparedArray, index + 1); } }
额外优化点
- 原代码中当
left[index] == right[index]时,greater会保留初始值0,如果你需要把相等的元素存入结果数组,可以把这部分逻辑改成:greater = left[index];(因为相等时左右值一样); - 可以添加参数校验,比如判断
left或right是否为null,避免空指针异常。
内容的提问来源于stack exchange,提问作者Gabriel Gavrilov
相关产品推荐
相关产品推荐

