程式語言 - LeetCode - C - 2300. Successful Pairs of Spells and Potions



參考資訊:
https://www.cnblogs.com/cnoodle/p/17281951.html

題目:


解答:

int mysort(const void *a, const void *b)
{
    return (*(int *)a) - (*(int *)b);
}
 
/**
 * Note: The returned array must be malloced, assume caller calls free().
 */
int* successfulPairs(int *spells, int spellsSize, int *potions, int potionsSize, long long success, int *returnSize)
{
    int i = 0;
    int *r = calloc(spellsSize, sizeof(int));
 
    qsort(potions, potionsSize, sizeof(int), mysort);
 
    for (i = 0; i < spellsSize; i++) {
        int left = 0;
        int right = potionsSize;
 
        while (left < right) {
            long long t = 0;
            int m = left + ((right - left) >> 1);
 
            t = (long long)spells[i] * potions[m];
 
            if (t < success) {
                left = m + 1;
            }
            else {
                right = m;
            }
        }
        r[i] = potionsSize - left;
    }
 
    *returnSize = spellsSize;
    return r;
}