2 回答
TA貢獻1804條經驗 獲得超7個贊
如何代替兩個,使用集合來存儲數組之一的存在?for loopsSetstockPrices
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 為 1.length)和 O(n + m) 性能時間(其中 m 為 2.length)。
TA貢獻1895條經驗 獲得超7個贊
在你的j循環中,你說的不是i<array2.lengthj<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...");
}
}
添加回答
舉報
