首页 > 解决方案 > 如何优化代码以通过一些测试用例

问题描述

我在hackerrank上做一些问题,我的代码确实通过了一些案例,但没有通过所有测试用例,有人可以帮我解决这个问题吗?这是问题的屏幕截图和我的部分代码

这是我的解决方案代码:

public static int mDivisor(List<Integer> arr, int threshold) {
        // arr = [1,5,7] threshold = 8
        // 1+ 5 + 7/ n < 8
        //1 + 5 + 7 < 8n
        // 13 < 8n
        // n = 1.625
        // n = 2
        // need more time to debug


        int minDivisor = 1;
        // find the minimum number to start division by based on our formula
        Optional<Integer> sArr = arr.stream().reduce((a,b)-> a+b);
        if(sArr.isPresent()){
            int sum = sArr.get();
            minDivisor = Math.round((float) sum/threshold);
        }

        // min greater should be greater than or equal to
        int totalSum; // to hold the value greater than the threshold
        do{
            totalSum = getSum(arr, minDivisor);
            if(totalSum > threshold){
                minDivisor += 1;
            }

        } while(totalSum > threshold);

        return minDivisor; // return the minDivisor

    }

    private static int getSum(List<Integer> a, int minDivisior){
        int t_sum = 0; // to hold total sum
        for(Integer n: a){
            t_sum += Math.round((float)n/minDivisior);
        }

        return t_sum; // return the total sum

    }
}

为我的阈值采样小数字:

@Test


       public void minimumDivisor() {

            //int[] arr = {1,5,7};
            List<Integer> arr1 = Arrays.asList(1,10,15,19);
            int threshold = 5;
            int expectedOutput = 9;
            Assertions.assertEquals(expectedOutput , mDivisor(arr1,threshold));

        }

标签: java

解决方案


推荐阅读