leetcode 2300 咒语和药水的成功对数
一、题目描述
二、解题思路
整体思路
可以采用排序+二分查找的方法来解决这个问题。
具体思路
(1)首先,对potions数组(药水)从小到大排序;
(2)遍历spells数组(咒语),计算与spells[i]乘积大于等于success的最小的乘数target(向上取整);
(3)利用lower_bound函数,二分查找potions数组(药水)中大于等于target的第一个数字的迭代器,potions.end()-it即为可与spells[i]配对的药水的数量,更新pairs[i]即可;
(4)遍历完spells数组后,直接返回pairs数组,即为所求。
三、代码实现
class Solution {
public:vector<int> successfulPairs(vector<int>& spells, vector<int>& potions, long long success) {int n=spells.size();int m=potions.size();vector<int> pairs(n,0);sort(potions.begin(),potions.end());for(int i=0;i!=n;i++){long long spell=spells[i];//向上取整long long target=(success+spell-1)/spell;//找到第一个大于等于target的数的迭代器auto it=lower_bound(potions.begin(),potions.end(),target);//计算potions数组中合法的药水的数量pairs[i]=potions.end()-it;}return pairs;}
};