
超时:
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
}