小编cks*_*rma的帖子

Arrays.stream(array_name).sum()比迭代方法慢吗?

我正在编写一个leetcode问题:使用Java 8 https://oj.leetcode.com/problems/gas-station/.

当我习惯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)) { …
Run Code Online (Sandbox Code Playgroud)

java algorithm performance java-8

10
推荐指数
2
解决办法
3955
查看次数

标签 统计

algorithm ×1

java ×1

java-8 ×1

performance ×1