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...");
}
}
添加回答
舉報