2 回答

TA贡献2051条经验 获得超10个赞
for loops使用Setcollection 来存储stockPrices数组中的一个而不是 two 怎么样?
public static List<Stocks> matching(Stocks[] one, Stocks[] two) {
Set<Integer> stockPrices = Arrays.stream(one)
.map(stock -> stock.stockPrice)
.collect(Collectors.toSet());
return Arrays.stream(two)
.filter(stock -> stockPrices.contains(stock.stockPrice))
.collect(Collectors.toList());
}
它使用O(n)额外内存(其中n是one.length)和O(n + m)性能时间(其中m是two.length)。

TA贡献1807条经验 获得超9个赞
在您的 j-loop 中,您说i<array2.length的是j<array2.length
public void matching ( Stocks[] array1, Stocks[] array2){
for (int i=0; i<array1.length;i++){
for (int j=0;
j<array2.length; //this j was an i
j++){
if (array1[i].stockPrice == array2[j].stockPrice){
System.out.println("It's a match at $" + array1[i].stockPrice);
}
System.out.println("still searching...");
}
System.out.println("first loop test...");
}
}
添加回答
举报