题目来源: LeetCode 75 30 天 JavaScript 挑战
2462. 雇佣 K 位工人的总代价
思路
使用两个优先队列存放 costs
左右两边的数据,每次判断左右队列头的大小,将小的数出列加到总代价上,一直到雇佣数为 0,返回总代价。
代码
js
/**
* @param {number[]} costs
* @param {number} k
* @param {number} candidates
* @return {number}
*/
var totalCost = function(costs, k, candidates) {
const left = new MinPriorityQueue();
const right = new MinPriorityQueue();
let cost = 0
let i = 0
let j = costs.length -1
while (k > 0) {
while(i <= j && left.size() < candidates) {
left.enqueue(costs[i++])
}
while(i <= j && right.size() < candidates) {
right.enqueue(costs[j--])
}
const min1 = left.size() > 0 ? left.front().element : Infinity
const min2 = right.size() > 0 ? right.front().element : Infinity
if (min1 <= min2) {
cost += left.dequeue().element
} else {
cost += right.dequeue().element
}
k--
}
return cost
};
374. 猜数字大小
思路
二分查找,每次寻找目标数在左还是右区间,当 guess(mid)
等于 0 时返回 left
代码
js
/**
* Forward declaration of guess API.
* @param {number} num your guess
* @return -1 if num is higher than the picked number
* 1 if num is lower than the picked number
* otherwise return 0
* var guess = function(num) {}
*/
/**
* @param {number} n
* @return {number}
*/
var guessNumber = function(n) {
let left = 1
let right = n
while(left < right) {
const mid = Math.floor(left + (right - left) / 2)
if (guess(mid) <= 0) {
right = mid
} else {
left = mid + 1
}
}
return left
};
2300. 咒语和药水的成功对数
思路
先将 potions
从小到大排序,遍历 spells
数组,每次通过二分查找找到 potions
数组全部强度有效的下标 left
,potions.length - left
表示有效数字的个数,添加到结果中。
代码
js
/**
* @param {number[]} spells
* @param {number[]} potions
* @param {number} success
* @return {number[]}
*/
var successfulPairs = function(spells, potions, success) {
potions.sort((a, b) => a - b)
let res = []
for(let i = 0; i < spells.length; i++) {
let mid
let left = 0
let right = potions.length
while(left < right) {
mid = Math.floor(left + (right - left) / 2)
if (potions[mid] * spells[i] >= success) {
right = mid
} else {
left = mid + 1
}
}
res.push(potions.length - left)
}
return res
};
本文完,感谢阅读🌹