关于力扣2025.10.8每日的收货
还是学习灵神的代码
class Solution {
public:vector<int> successfulPairs(vector<int>& spells, vector<int>& potions, long long success) {ranges::sort(potions);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;}
};
这里有一个减枝,也就是当target大于potions的最大值时,就直接返回0。
否则二分大于等于x 的第一个位置,然后计算比x 大的数的数量。
而灵神的第二种方法打开了我的视野,也就是在这种值域比较小的时候,关注值域即可。
而快速找到数组中大于某一个值的数的数量,可以用O(n +U)的复杂度预处理,然后用O(1)查询。
代码如下:
class Solution {
public:vector<int> successfulPairs(vector<int>& spells, vector<int>& potions, long long success) {int mx = ranges::max(potions);vector<int> cnt(mx + 1);for (int y : potions) {cnt[y]++; // 统计每种药水的出现次数}// 计算 cnt 的后缀和for (int i = mx - 1; i >= 0; i--) {cnt[i] += cnt[i + 1];}// 计算完毕后,cnt[i] 就是 potions 值 >= i 的药水个数for (int& x : spells) {long long low = (success - 1) / x + 1;x = low <= mx ? cnt[low] : 0;}return spells;}
};作者:灵茶山艾府
链接:https://leetcode.cn/problems/successful-pairs-of-spells-and-potions/solutions/1595712/by-endlesscheng-1kbp/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
慢慢进步 今天晚上争取vp一把div3