简体   繁体   English

用递归方法填充数组

[英]fill array with recursive method

I m trying to create a function to fill array with the recursive method in java this is my code (the parameter x is the size of the array):我正在尝试创建一个 function 以使用 java 中的递归方法填充数组这是我的代码(参数 x 是数组的大小):

public int[] genArr(int[] nums,int idx,int x){
    if(idx>x){
        return nums;
    }
   
    else{
    nums[idx] = idx;
    return genArr(nums,idx++,x--);
    }
     
}

but when run my function I have stackOverflow error.但是当运行我的 function 时出现 stackOverflow 错误。

Somebody can help me?有人可以帮助我吗?

There are a couple of problems there:那里有几个问题:

  1. The stack overflow issue you asked about.您询问的堆栈溢出问题。

  2. The basic logic of the method.方法的基本逻辑。

The first problem is that getArr(num, idx++, x--) uses the postfix increment operator (the ++ is after the operand), so it passes the current value of idx to getArr and then increments the parameter's value.第一个问题是getArr(num, idx++, x--)使用后缀递增运算符( ++在操作数之后),因此它将idx当前值传递给getArr然后递增参数的值。 But nothing ever uses the incremented parameter value.但是没有任何东西使用增加的参数值。 So if idx is 0 and x is 10 , you're endlessly calling getArr(nums, 0, 10) until you overflow the stack.因此,如果idx0x10 ,则您将无休止地调用getArr(nums, 0, 10)直到堆栈溢出。 If you were going to use the increment operator, it would need to be the prefix increment operator where the ++ is in front of the operand ( ++idx ), but there's no reason to use the increment operator: just use idx + 1 .如果您要使用增量运算符,它需要是前缀增量运算符,其中++在操作数( ++idx )前面,但没有理由使用增量运算符:只需使用idx + 1 .

The second problem is that even if you fix the above, by increasing idx and decreasing x and stopping when idx > x is true, you're going to miss out filling in most of the array.第二个问题是,即使您解决了上述问题,通过增加idx并减少x并在idx > x为真时停止,您将错过填充大部分数组。 For instance, if you started with idx at 0 and x at 10 , your code would stop when idx was 6 and x was 4 , leaving the last several slots of your array uninitialized: [0, 1, 2, 3, 4, 5, 0, 0, 0, 0] .例如,如果您从idx0x10开始,您的代码将在idx6x4时停止,而数组的最后几个插槽未初始化: [0, 1, 2, 3, 4, 5, 0, 0, 0, 0] Instead, get rid of x entirely and make idx >= nums.length your termination condition:相反,完全摆脱x并使idx >= nums.length您的终止条件:

public int[] genArr(int[] nums, int idx) {
// #2 No `x` −−−−−−−−−−−−−−−−−−−−−−−−−−^
    if (idx >= nums.length) {
// #2 −−−−−−^^^^^^^^^^^^^^ compare with `nums.length`
        return nums;
    } else {
        nums[idx] = idx;
        return genArr(nums, idx + 1);
// #1 −−−−−−−−−−−−−−−−−−−−−−^^^^^^^
    }
}

Technically, you could use == rather than >= because you only ever add 1 to idx , but I tend to be paranoid about array access guards like that and use >= instead (in case logic changes and we add more than 1 at some point).从技术上讲,您可以使用==而不是>=因为您只会将1添加到idx ,但我倾向于对这样的数组访问保护持偏执态度并使用>=代替(以防逻辑更改并且我们在某些情况下添加超过1观点)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM