Leetcode-2300

Successful Pairs of Spells and Potions

Time complexity: $O(N\log n+M\log m)$

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>
#include <vector>
#include <algorithm>

class Solution {
public:
    std::vector<int> successfulPairs(std::vector<int>& spells, std::vector<int>& potions, long long success) {
        std::sort(potions.begin(), potions.end());
        int n = potions.size(), mid;
        for (int& spell : spells) {
            long long target = (success - 1) / spell + 1;
            int a = 0, b = n - 1;
            while (b > a) {
                mid = (a + b) / 2;
                if (potions[mid] >= target) {
                    b = mid;
                }
                else {
                    a = mid + 1;
                }
            }
            spell = (n - a) * (potions[a] >= target);
        }
        return spells;
    }
};

Leetcode-2300