力扣2300.咒语和药水的成功对数
-
排序 + 二分
- 对于能整除的数 -1以后一起处理
- 可以在原数组直接修改
-
class Solution { public: vector<int> successfulPairs(vector<int>& spells, vector<int>& potions, long long success) { sort(potions.begin(),potions.end()); for(int &x:spells) { long long target = (success-1)/x; if(target < potions.back()) x = potions.end() - ranges::upper_bound(potions,(int)target); else x = 0; } return spells; } };
- 也可以另开一个新的
-
class Solution { public: vector<int> successfulPairs(vector<int>& spells, vector<int>& potions, long long success) { vector<int> res; sort(potions.begin(),potions.end()); for(int i=0;i<spells.size();i++) { long long target = (success-1)/spells[i]; if(target < potions.back()) res.emplace_back((potions.end() - ranges::upper_bound(potions,(int)target))); else res.emplace_back(0); } return res; } };