java - 如何优化代码以通过一些测试用例
问题描述
我在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));
}
解决方案
推荐阅读
- python - 如何获得代理的每日标准划分?
- c# - 如何模拟或设置通常在启动时设置为静态属性的单元测试的值?
- java - 尽管成功使用了验证和断言,但根据测试覆盖率未覆盖行
- ios - Payu 不在 WKWebview 目标 c 中工作
- javascript - 如何在js中检查字符串是否包含任何值(无论是符号还是任何东西)?
- c# - Asp.net 核心问题中的分页,仅获取 10 项而不使其更快?
- html - 一种形式,一种模式和 1 个输入
- python - 如何退出 discord.py on_message 功能?
- javascript - 按任意对象值对数组进行排序(不是升序或降序)
- python - 如何打印腌制字典的偏移量