2300.Successful Pairs of Spells and Potions

25 年 8 月 25 日 星期一
249 字
2 分钟

2300. 咒语和药水的成功对数

Screenshot 2026-02-26 at 4.39.37 pm

超时:

js
/**
 * @param {number[]} spells
 * @param {number[]} potions
 * @param {number} success
 * @return {number[]}
 */

const binarySearch = (left, right, target, arr) => {
  while (left < right) {
    const mid = Math.floor((left + right) / 2)
    if (arr[mid] < target) {
      left = mid + 1
    } else {
      right = mid
    }
  }
  return left
}
var successfulPairs = function (spells, potions, success) {
  const ans = []
  potions.sort((a, b) => a - b) // in-place
  for (const s of spells) {
    const times = potions.map((item) => {
      // ⚠️这里O(n^2),换成除法
      return s * item
    })
    ans.push(times.length - binarySearch(0, times.length, success, times))
  }
  return ans
}

不超时的版本,直接用const target = success / s 当target。

js
/**
 * @param {number[]} spells
 * @param {number[]} potions
 * @param {number} success
 * @return {number[]}
 */

const binarySearch = (left, right, target, arr) => {
  while (left < right) {
    const mid = Math.floor((left + right) / 2)
    if (arr[mid] < target) {
      left = mid + 1
    } else {
      right = mid
    }
  }
  return left
}
var successfulPairs = function (spells, potions, success) {
  const ans = []
  potions.sort((a, b) => a - b) // in-place
  for (const s of spells) {
    const target = success / s
    ans.push(potions.length - binarySearch(0, potions.length, target, potions))
  }
  return ans
}

文章标题:2300.Successful Pairs of Spells and Potions

文章作者:Sirui Chen

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

最后修改时间:


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