【发布时间】: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 发帖并描述具体问题。
-
reduce和filter函数是你的朋友 -
newArray[i] = arrayToCollapse[i * 2] + arrayToCollapse[i * 2 + 1]; -
遗憾的是我无法使用这些,因为我无法超越我在课堂上的位置。
-
谢谢@Johnny,我也看到了下面的答案。