我被編碼本文給出了問題:https://oj.leetcode.com/problems/gas-station/使用Java 8.Arrays.stream(array_name).sum()比迭代方法慢嗎?
我的解決方案得到了TLE當我用Arrays.stream(integer_array).sum()
計算總和,而相同的溶液得到了使用迭代計算在陣列元素的總和接受。這個問題的最佳時間複雜度是O(n),當使用Java 8的流API時,我很驚訝地得到TLE。我只在O(n)中實現瞭解決方案。
import java.util.Arrays;
public class GasStation {
public int canCompleteCircuit(int[] gas, int[] cost) {
int start = 0, i = 0, runningCost = 0, totalGas = 0, totalCost = 0;
totalGas = Arrays.stream(gas).sum();
totalCost = Arrays.stream(cost).sum();
// for (int item : gas) totalGas += item;
// for (int item : cost) totalCost += item;
if (totalGas < totalCost)
return -1;
while (start > i || (start == 0 && i < gas.length)) {
runningCost += gas[i];
if (runningCost >= cost[i]) {
runningCost -= cost[i++];
} else {
runningCost -= gas[i];
if (--start < 0)
start = gas.length - 1;
runningCost += (gas[start] - cost[start]);
}
}
return start;
}
public static void main(String[] args) {
GasStation sol = new GasStation();
int[] gas = new int[] { 10, 5, 7, 14, 9 };
int[] cost = new int[] { 8, 5, 14, 3, 1 };
System.out.println(sol.canCompleteCircuit(gas, cost));
gas = new int[] { 10 };
cost = new int[] { 8 };
System.out.println(sol.canCompleteCircuit(gas, cost));
}
}
該溶液得到接受時, 我評論以下兩行:(計算總和使用流)
totalGas = Arrays.stream(gas).sum();
totalCost = Arrays.stream(cost).sum();
並取消以下兩行(計算總和使用迭代):
//for (int item : gas) totalGas += item;
//for (int item : cost) totalCost += item;
現在解決方案被接受。爲什麼Java中的流媒體API 8對於較大的輸入比基元的迭代要慢?
結果[here](http://stackoverflow.com/questions/16635398/java-8-iterable-foreach-vs-foreach-loop/25855691#25855691)是計算在集合(列表)而不是基元上。基元沒有像list.forEach((i) - > doIt(i)); ,相反,我們必須使用Arrays工具。對於集合,Java流,並行和縮減比迭代更快。我仍然懷疑原始數據流的結果比正常迭代更慢。 和leetcode測試我的解決方案對巨大的數據集。 – cksharma