1283. Find the Smallest Divisor Given a Threshold
- 找到答案空间 [1, max(nums)]
- 二分查找答案空间
js
/**
* @param {number[]} nums
* @param {number} threshold
* @return {number}
*/
const check = (n, threshold, nums) => {
return (
nums
.map((item) => {
return Math.ceil(item / n)
})
.reduce((acc, cur) => acc + cur) <= threshold
)
}
var smallestDivisor = function (nums, threshold) {
let left = 1
let right = Math.max(...nums)
while (left < right) {
const mid = Math.floor((left + right) / 2)
if (check(mid, threshold, nums)) {
right = mid
} else {
left = mid + 1
}
}
return right
}