【问题标题】:Collapsing an array折叠数组
【发布时间】:2020-09-23 21:37:16
【问题描述】:

我需要让这个方法接受一个数组并将每 2 个数字相加(不会将相同的数字添加两次)并创建一个新数组以返回,如果有奇数个元素,奇数将最后添加。它目前没有添加正确的数字。

代码:

public static int[] collapse(int[] arrayToCollapse) {

    // Properties
    int[] newArray = new int[(arrayToCollapse.length / 2) + (arrayToCollapse.length % 2)];

    // Set each elements for the new array.
    for(int i = 0; i < arrayToCollapse.length / 2 ; i++) {

        // Set the current index of the new array to the next two elements of the passed in array.
        newArray[i] += arrayToCollapse[i * 2] + arrayToCollapse[i * 2];

    }

    // Set the last element of the new array if the array passed in was odd.
    if(arrayToCollapse.length % 2 == 1) {

        newArray[newArray.length - 1] = arrayToCollapse[arrayToCollapse.length - 1];

    }

    // Return the array
    return newArray;

}

【问题讨论】:

  • 提供的代码有什么问题?请edit 发帖并描述具体问题。
  • reducefilter函数是你的朋友
  • newArray[i] = arrayToCollapse[i * 2] + arrayToCollapse[i * 2 + 1];
  • 遗憾的是我无法使用这些,因为我无法超越我在课堂上的位置。
  • 谢谢@Johnny,我也看到了下面的答案。

标签: java arrays


【解决方案1】:

这个:

newArray[i] += arrayToCollapse[i * 2] + arrayToCollapse[i * 2];

应该是:

newArray[i] = arrayToCollapse[i * 2] + arrayToCollapse[(i * 2) + 1];

【讨论】:

    猜你喜欢
    • 2018-12-24
    • 2013-03-10
    • 2014-03-10
    • 2010-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-11
    • 2020-02-09
    相关资源
    最近更新 更多