[LeetCode] 2300. Successful Pairs of Spells and Potions
You are given two positive integer arrays spells and potions, of length n and m respectively, where spells[i] represents the strength of the ith spell and potions[j] represents the strength of the jth potion.
You are also given an integer success. A spell and potion pair is considered successful if the product of their strengths is at least success.
Return an integer array pairs of length n where pairs[i] is the number of potions that will form a successful pair with the ith spell.
Example 1:
Input: spells = [5,1,3], potions = [1,2,3,4,5], success = 7
Output: [4,0,3]
Explanation:
- 0th spell: 5 * [1,2,3,4,5] = [5,10,15,20,25]. 4 pairs are successful.
- 1st spell: 1 * [1,2,3,4,5] = [1,2,3,4,5]. 0 pairs are successful.
- 2nd spell: 3 * [1,2,3,4,5] = [3,6,9,12,15]. 3 pairs are successful.
Thus, [4,0,3] is returned.
Example 2:
Input: spells = [3,1,2], potions = [8,5,8], success = 16
Output: [2,0,2]
Explanation:
- 0th spell: 3 * [8,5,8] = [24,15,24]. 2 pairs are successful.
- 1st spell: 1 * [8,5,8] = [8,5,8]. 0 pairs are successful.
- 2nd spell: 2 * [8,5,8] = [16,10,16]. 2 pairs are successful.
Thus, [2,0,2] is returned.
Constraints:
n == spells.length
m == potions.length
1 <= n, m <= 105
1 <= spells[i], potions[i] <= 105
1 <= success <= 1010
咒语和药水的成功对数。
给你两个正整数数组 spells 和 potions ,长度分别为 n 和 m ,其中 spells[i] 表示第 i 个咒语的能量强度,potions[j] 表示第 j 瓶药水的能量强度。同时给你一个整数 success 。一个咒语和药水的能量强度 相乘 如果 大于等于 success ,那么它们视为一对 成功 的组合。
请你返回一个长度为 n 的整数数组 pairs,其中 pairs[i] 是能跟第 i 个咒语成功组合的 药水 数目。
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/successful-pairs-of-spells-and-potions
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路
思路是排序 + 二分。题意不难理解,注意看第一个例子,当发现 5 * 2 = 10 > 4 的时候,包括 2 在内后面所有的乘积都可以被判为 success,所以这里考虑对 potion 数组排序。这道题属于在答案上二分的题。
第一次做的时候用了两层 for 循环,发现最后有几个很长的 case 超时。优化的思路只能往二分上靠。这道题能用二分优化的前提是被二分的数据是有序的,因为我们对 potion 数组已经排过序,所以可以用二分。
复杂度
时间O(nlogm)
空间O(n) - output array
代码
Java实现
class Solution {
public int[] successfulPairs(int[] spells, int[] potions, long success) {
Arrays.sort(potions);
int n = spells.length;
int m = potions.length;
int[] res = new int[n];
for (int i = 0; i < n; i++) {
long spell = (long) spells[i];
int left = 0;
int right = m;
while (left < right) {
int mid = left + (right - left) / 2;
if (spell * potions[mid] < success) {
left = mid + 1;
} else {
right = mid;
}
}
res[i] = m - left;
}
return res;
}
}