我正在寻找有关如何解决此问题或我哪里出错的提示。
问题如下:编写一个名为stretch的静态方法,它接受一个整数数组作为参数,并返回一个两倍于原始数组的新数组,用一对整数替换原始数组中的每个整数,每个整数原来的一半。如果原始数组中的数字是奇数,则新对中的第一个数字应比第二个数字大一个,以便总和等于原始数字。例如,如果名为 list 的变量引用存储值 {18, 7, 4, 24, 11} 的数组,则调用 stretch(list) 应返回一个包含 {9, 9, 4, 3, 2 , 2, 12, 12, 6, 5}。 (数字 18 拉伸(stretch)为 9、9,数字 7 拉伸(stretch)为 4、3,数字 4 拉伸(stretch)为 2、2,数字 24 拉伸(stretch)为 12、12,数字 11 拉伸(stretch)为 6 ,5。) 使用以下类测试您的代码: 导入java.util.*;
public class TestStretch {
public static void main(String[] args) {
int[] list = {18, 7, 4, 14, 11};
int[] list2 = stretch(list);
System.out.println(Arrays.toString(list)); // [18, 7, 4, 24, 11]
System.out.println(Arrays.toString(list2)); // [9, 9, 4, 3, 2, 2, 7, 7, 6, 5]
}
// your code goes here
}
这就是我目前所拥有的,但它工作得不太正常...我有一种感觉,这就是我使用 int i 和 int j 的方式,但我不知道该如何修复它,所以它按预期工作。
import java.util.*;
public class TestStretch {
public static void main(String[] args) {
int[] list = {18, 7, 4, 14, 11};
int[] list2 = stretch(list);
System.out.println(Arrays.toString(list)); // [18, 7, 4, 24, 11]
System.out.println(Arrays.toString(list2)); // [9, 9, 4, 3, 2, 2, 7, 7, 6, 5]
}
public static int[] stretch(int[] array){
int length = array.length;
int[] newArray = new int[array.length*2];
for(int i = 0; i< length; i=i+2){
int j = 0;
if(array[i] % 2 == 0){
newArray[i] = (array[j]/2);
newArray[i+1] = newArray[i];
j++;
} else{
newArray[i] = (array[j]/2);
newArray[i+1] = (newArray[i] + 1);
j++;
}
}
return newArray;
}
}
我得到的输出是:
[18, 7, 4, 14, 11]
[9, 9, 9, 9, 9, 10, 0, 0, 0, 0]
而不是:
[18, 7, 4, 24, 11]
[9, 9, 4, 3, 2, 2, 7, 7, 6, 5]
最佳答案
有几个错误:
- 循环仅迭代到数组的一半,并跳过 2 个元素
j
的值在每次迭代中重置为 0
此外,算法还可以简化:
- 对于输入中的每个索引
i
,您希望在目标位置2 * i
和2 * i + 1
处设置. - 要设置的第二个值就是原始值除以 2,并进行整数截断
- 要设置的第一个值与第二个值相同,如果除以 2 留下余数,则 +1
纠正上述问题并简化实现:
int[] newArray = new int[array.length * 2];
for (int i = 0; i < array.length; i++) {
newArray[2 * i] = array[i] / 2 + array[i] % 2;
newArray[2 * i + 1] = array[i] / 2;
}
return newArray;
关于java - 数组处理(拉伸(stretch))方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47144348/