给你两个正整数数组 spells
和 potions
,长度分别为 n
和 m
,其中 spells[i]
表示第 i
个咒语的能量强度,potions[j]
表示第 j
瓶药水的能量强度。
同时给你一个整数 success
。一个咒语和药水的能量强度 相乘 如果 大于等于 success
,那么它们视为一对 成功 的组合。
请你返回一个长度为 n
的整数数组 pairs
,其中 pairs[i]
是能跟第 i
个咒语成功组合的 药水 数目。
示例 1:
输入:spells = [5,1,3], potions = [1,2,3,4,5], success = 7 输出:[4,0,3] 解释: - 第 0 个咒语:5 * [1,2,3,4,5] = [5,10,15,20,25] 。总共 4 个成功组合。 - 第 1 个咒语:1 * [1,2,3,4,5] = [1,2,3,4,5] 。总共 0 个成功组合。 - 第 2 个咒语:3 * [1,2,3,4,5] = [3,6,9,12,15] 。总共 3 个成功组合。 所以返回 [4,0,3] 。
示例 2:
输入:spells = [3,1,2], potions = [8,5,8], success = 16 输出:[2,0,2] 解释: - 第 0 个咒语:3 * [8,5,8] = [24,15,24] 。总共 2 个成功组合。 - 第 1 个咒语:1 * [8,5,8] = [8,5,8] 。总共 0 个成功组合。 - 第 2 个咒语:2 * [8,5,8] = [16,10,16] 。总共 2 个成功组合。 所以返回 [2,0,2] 。
提示:
n == spells.length
m == potions.length
1 <= n, m <= 105
1 <= spells[i], potions[i] <= 105
1 <= success <= 1010
方法一:二分查找
class Solution:
def successfulPairs(
self, spells: List[int], potions: List[int], success: int
) -> List[int]:
potions.sort()
m = len(potions)
return [m - bisect_left(potions, success, key=lambda x: s * x) for s in spells]
class Solution {
public int[] successfulPairs(int[] spells, int[] potions, long success) {
Arrays.sort(potions);
int m = potions.length, n = spells.length;
int[] ans = new int[n];
for (int i = 0; i < n; ++i) {
int left = 0, right = m;
while (left < right) {
int mid = (left + right) >> 1;
if ((long) spells[i] * potions[mid] >= success) {
right = mid;
} else {
left = mid + 1;
}
}
ans[i] = m - left;
}
return ans;
}
}
class Solution {
public:
vector<int> successfulPairs(vector<int>& spells, vector<int>& potions, long long success) {
sort(potions.begin(), potions.end());
int m = potions.size();
vector<int> ans;
for (int& s : spells) {
int left = 0, right = m;
while (left < right) {
int mid = (left + right) >> 1;
if (1ll * s * potions[mid] >= success)
right = mid;
else
left = mid + 1;
}
ans.push_back(m - left);
}
return ans;
}
};
func successfulPairs(spells []int, potions []int, success int64) []int {
sort.Ints(potions)
m := len(potions)
var ans []int
for _, s := range spells {
left, right := 0, m
for left < right {
mid := (left + right) >> 1
if int64(s*potions[mid]) >= success {
right = mid
} else {
left = mid + 1
}
}
ans = append(ans, m-left)
}
return ans
}
function successfulPairs(
spells: number[],
potions: number[],
success: number,
): number[] {
const n = spells.length,
m = potions.length;
potions.sort((a, b) => a - b);
let pairs = new Array(n);
let hashMap = new Map();
for (let i = 0; i < n; i++) {
const target = Math.ceil(success / spells[i]);
let idx = hashMap.get(target);
if (!idx) {
idx = searchLeft(potions, 0, m, target);
hashMap.set(target, idx);
}
pairs[i] = m - idx;
}
return pairs;
}
function searchLeft(nums, left, right, target) {
while (left < right) {
let mid = (left + right) >> 1;
if (nums[mid] >= target) {
right = mid;
} else {
left = mid + 1;
}
}
return left;
}