Leetcode—2300.咒语和药水的成功对数【中等】

2023每日刷题(二十五)

Leetcode—2300.咒语和药水的成功对数

Leetcode—2300.咒语和药水的成功对数【中等】_第1张图片

排序+二分实现代码

class Solution {
public:
    int lower_bound(vector<int> &potions, long long target) {
        int n = potions.size();
        int left = 0, right = n;
        int mid = left + (right - left) / 2;
        while(left < right) {
            mid = left + (right - left) / 2;
            if(potions[mid] < target) {
                left = mid + 1;
            } else {
                right = mid;
            }
        }
        return left;
    }

    vector<int> successfulPairs(vector<int>& spells, vector<int>& potions, long long success) {
        sort(potions.begin(), potions.end());
        int n = spells.size();
        int len = potions.size();
        for(int i = 0; i < n; i++) {
            long long tar = 1 + (success - 1) / spells[i];
            int cnt = lower_bound(potions, tar);
            int res = len - cnt;
            spells[i] = res;
        }
        return spells;
    }
};

运行结果

Leetcode—2300.咒语和药水的成功对数【中等】_第2张图片
之后我会持续更新,如果喜欢我的文章,请记得一键三连哦,点赞关注收藏,你的每一个赞每一份关注每一次收藏都将是我前进路上的无限动力 !!!↖(▔▽▔)↗感谢支持!

你可能感兴趣的:(LeetCode刷题,leetcode,算法,职场和发展,二分法,排序,c++,经验分享)