使结果不超过阈值的最小除数
使结果不超过阈值的最小除数
#resource / algorithm
#type / snippet
#status / evergreen
#source / leetcode
#algo / binary-search
[!info] related notes 算法面试题型 MOC 二分查找
使结果不超过阈值的最小除数
题目
1283. 使结果不超过阈值的最小除数 - 力扣(LeetCode)
题解
二分查找
首先确定题目解是在 [1, max(nums)] 之间,然后通过二分法查找。
var smallestDivisor = function(nums, threshold) {
function compute(ans) {
let sun = 0;
for (const a of nums) {
sun += Math.ceil(a/ans);
}
if (sun <= threshold) return true;
return false;
}
let n = nums.length;
let left = 1, right = Math.max(...nums);
while (left <= right) {
mid = Math.floor((left + right)/2);
if (compute(mid)) {
right = mid - 1;
} else {
left = mid + 1;
}
}
return left;
};