【发布时间】:2015-01-13 15:46:09
【问题描述】:
我正在编写一个 leetcode 问题:https://oj.leetcode.com/problems/gas-station/ 使用 Java 8。
当我使用Arrays.stream(integer_array).sum() 计算总和时,我的解决方案获得了 TLE,而使用迭代计算数组中元素的总和时,相同的解决方案被接受。这个问题的最佳时间复杂度是 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 8 中的流式 API 对于大输入比原语迭代慢?
【问题讨论】:
-
here 的结果是针对集合(列表)而不是基元计算的。原语没有类似 list.forEach((i) -> doIt(i)); ,相反我们必须使用 Arrays 实用程序。对于集合,Java 流式处理、并行性和缩减比迭代更快。我仍然怀疑原始流的结果如何比正常迭代慢。 leetcode 针对庞大的数据集测试我的解决方案。
标签: java performance algorithm java-8