问题描述
给定一个整数数组,创建一个新数组,使得新数组索引 i
处的每个元素都是原始数组中除 i
处的数字之外的所有数字的乘积。
例如,如果我们的输入是 [1,2,3,4,5]
,那么预期的输出就是 [120,60,40,30,24]
。如果我们的输入是 [3,1]
,则预期输出将是 [2,6]
。
注意:不要使用除法。
import java.util.Scanner;
public class Productofarray {
public static void main(String[] args) {
Scanner sc = new Scanner(system.in);
int prod = 1,i,j = 0;
System.out.println("How many values do you want to enter");
int n = sc.nextInt();
int a[] = new int[n];
int a2[] = new int[n];
System.out.println("Input " + n + " values:");
for (i = 0; i < n; i++) {
a[i] = sc.nextInt();
}
for (i = 0; i < n; i++) {
inner:
while (j < n) {
if (a[j] == a[i]) {
j++;
continue inner;
}
prod *= a[j];
}
a2[i] = prod;
System.out.println(a2[i]);
}
}
}
我已经编写了这段代码,但问题是它一直在运行,它永远不会结束,有人可以帮助我在这里做错了什么。
解决方法
因为当 i!=j 时你不会增加 j。此外,您应该检查 i==j 而不是 a[i]==a[j]。
,这应该会让你更接近;正如 Maneesh 的回答所指出的那样,您没有检查您是否处于当前索引,即 arrowButton.forEach((el) =>
el.addEventListener("click",(event) => {
const subMenu = event.target.parentElement.querySelector(
".options__container--option"
);
subMenu.classList.toggle("active");
})
);
而不是 i == j
。您也不需要标签,建议您完全避免使用它们。
a[i]==a[j]
我花了一秒钟才弄明白,但这里有一个使用 Java 8 Stream API 的示例:
for(int i=0; i<n; i++)
{
// this loop can be replaced with a stream.reduce - however that seems to require copying a1 in place to remove the element at index i first as reduce doesn't seem to pass the current index.
for(int j = 0; j < n; j++) {
if(j i) continue;
a2[i] *= a1[j];
}
System.out.println(a2[i]);
}
我还没有测试过,但它应该可以工作(也许需要做一两次调整)。这。它的要点是创建一个新数组 (for(int i=0; i<n; i++) // for i -> n
{
final int currentIndex = i;
a2[i] = IntStream.range(0,a1.length)
.filter(index -> index != currentIndex) // ingore the curent index
.map(index -> a1[index]) // map the remaining indecies to the values
.reduce((subTotal,current) -> subTotal * current); // reduce to a single int through multiplication.
}
System.out.println(a2[i]);
),其中包含给定数组的每个元素,但 currentIndex (IntStream.range
) 处的元素,然后将元素相乘 (.filter().map()
)。请注意,此解决方案通过 for 循环为每次迭代创建一个新数组,对于非常大的数组,内存效率低下。