如何调试无效的HackerRank代码?

时间:2020-01-21 04:32:48

标签: java algorithm

我在一个非常简单的问题上的代码测试失败。但是,即使提交了错误的解决方案,我也无法发现我的逻辑出了什么问题。我想从这次失败中学习,以便下次可以做得更好,但是没有在线解决此问题的方法。

我的逻辑有问题吗?

我通过了2/8个测试用例,但失败的有大量输入或无法调试的隐藏输入。我的逻辑似乎适用于我可以手工查找的情况。

Problem and my solution

我的解决方案的代码如下:

public static int efficientJanitor(List<Float> weight)
{
    int trips = 0;
    int currIndex = 0;
    float currWeight = 0;

    //Loop until we hit end of List
    while (currIndex < weight.size())
    {
        System.out.println("currIndex weight is: " + weight.get(currIndex));
        currWeight = currWeight + weight.get(currIndex);

        //If we still have room in the current bag
        if (currWeight < 3.00)
        {
            currIndex++;
        }

        //We have no more room in the bag, increment trips, DONT increment 
        //currIndex so that we add weight at currIndex
        //in next loop's iteration.

        else if (currWeight >= 3.00)
        {
            trips++;
            System.out.println("Trips is: " + trips);
            currWeight = 0;
        }
    }

    System.out.println("currWeight is: " + currWeight);
    //Possible to have another bag left after while loop terminates,
    //since loop could end without handling any 
    //remaining weight

    if (currWeight >= 1.01 && currWeight <= 3.00)
    {
        trips++;
    }

    return trips; 
}

1 个答案:

答案 0 :(得分:3)

似乎您正在使用 greedy 算法失败,例如,在这种情况下:[1.3 3 1.3 3]进行4次旅行,而可能进行3次旅行。

尝试对重量列表进行排序。然后为最小的项目找到最大的配对项目。重复第二项,依此类推。 (在这里,双索引方法看起来不错)

所以[1.1 1.4 1.45 1.5 1.9 2 2.5]给出了对1.1+1.91.4 +1.5

相关问题