1283. Find the Smallest Divisor Given a Threshold

26 年 2 月 26 日 星期四
113 字
1 分钟

1283. Find the Smallest Divisor Given a Threshold

  1. 找到答案空间 [1, max(nums)]
  2. 二分查找答案空间
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
}

文章标题:1283. Find the Smallest Divisor Given a Threshold

文章作者:Sirui Chen

文章链接:https://blog.siruichen.me/posts/1283_find_the_smallest_divisor_given_a_threshold[复制]

最后修改时间:


商业转载请联系站长获得授权,非商业转载请注明本文出处及文章链接,您可以自由地在任何媒体以任何形式复制和分发作品,也可以修改和创作,但是分发衍生作品时必须采用相同的许可协议。
本文采用CC BY-NC-SA 4.0进行许可。