你如何进行成对乘法?
How do you do pairwise muliplication?
所以我真的是编码新手 (JAVA),我需要进行成对乘法运算。
例如,考虑列表 [ 2, 5, 6]
返回的列表应该是 [10, 12, 30]
那么如何确保它们只与其他数字相乘而不与它们自己相乘?
如果我没看错你的问题,那么你似乎想使用 for-loop
,并且你正在尝试获取数组中除当前元素之外的所有元素的乘积。
如果是这样,那么你的例子应该是:
[2, 5, 6] => [30, 12, 10]
这是我的解决方案:
public int[] pairWise(int[] numbers) {
int[] res = new int[numbers.length];
for (int i = 0; i < numbers.length; i++) {
int[] temp = new int[numbers.length - 1];
System.arraycopy(numbers, 0, temp, 0, i);
System.arraycopy(numbers, i + 1, temp, i, numbers.length - i - 1);
int product = 1;
for (int j = 0; j < temp.length; j++) {
product *= temp[j];
}
res[i] = product;
}
return res;
}
这个解决方案非常低效,因为它使用了 2 for-loops
,这使得它 O(n2)。
所以我真的是编码新手 (JAVA),我需要进行成对乘法运算。 例如,考虑列表 [ 2, 5, 6] 返回的列表应该是 [10, 12, 30]
那么如何确保它们只与其他数字相乘而不与它们自己相乘?
如果我没看错你的问题,那么你似乎想使用 for-loop
,并且你正在尝试获取数组中除当前元素之外的所有元素的乘积。
如果是这样,那么你的例子应该是:
[2, 5, 6] => [30, 12, 10]
这是我的解决方案:
public int[] pairWise(int[] numbers) {
int[] res = new int[numbers.length];
for (int i = 0; i < numbers.length; i++) {
int[] temp = new int[numbers.length - 1];
System.arraycopy(numbers, 0, temp, 0, i);
System.arraycopy(numbers, i + 1, temp, i, numbers.length - i - 1);
int product = 1;
for (int j = 0; j < temp.length; j++) {
product *= temp[j];
}
res[i] = product;
}
return res;
}
这个解决方案非常低效,因为它使用了 2 for-loops
,这使得它 O(n2)。