Two Pointers 双指针
About 2 min
Two Pointers 双指针
左右指针
T2300. 咒语和药水的成功对数
给你两个正整数数组 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.lengthm == potions.length1 <= n, m <= 1051 <= spells[i], potions[i] <= 1051 <= success <= 1010
我的答案
看题目规模乘出来是超过int的大小的,因此得用long。
对数组spells下标按照其位置上的能量强度进行升序排序,假设其排序后的数组为 idx,对数组 potions按照能量强度进行降序排序。
对spells进行从左到右用i遍历,对potions从做到右用j遍历,对于每个i如果与j相乘后小于了success,则对于j之前的所有元素都会大于,j就是答案;这时把i往前走越来越大,对于j而言也是单调不减向右。
这题用二分法来解更为简单
class Solution {
public int[] successfulPairs(int[] spells, int[] potions, long success) {
int n = spells.length, m = potions.length;
int[] res = new int[n];
int[][] idx = new int[n][2];
for (int i = 0; i < n; ++i) {
idx[i][0] = spells[i];
idx[i][1] = i;
}
Arrays.sort(potions);
for (int i = 0, j = m - 1; i < j; ++i, --j) {
int temp = potions[i];
potions[i] = potions[j];
potions[j] = temp;
}
Arrays.sort(idx, (a, b) -> a[0] - b[0]);
for (int i = 0, j = 0; i < n; ++i) {
int p = idx[i][1];
int v = idx[i][0];
while (j < m && (long) potions[j] * v >= success) {
++j;
}
res[p] = j;
}
return res;
}
}
作者:力扣官方题解
链接:https://leetcode.cn/problems/successful-pairs-of-spells-and-potions/solutions/2477429/zhou-yu-he-yao-shui-de-cheng-gong-dui-sh-a22z/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。