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

题目如下

数据范围

示例

复制代码
注意到n和m的长度最长达到10的5次方所以时间复杂度为n方的必然超时。
因为题目要求我们返回每个位置的spell对应的有效对数所以我们只需要找到第一个有效的药水就行,这里可以先对potions排序随后使用二分查找把时间复杂度压到nlogn就不会超时。

通过代码

cpp 复制代码
class Solution {
public:
       int findl(vector<int>& nums,long long v,long long target){
        int n = nums.size();
        int l = 0,r = n - 1;
        int mid = (l + r) / 2;
        
        
        while(l < r){
            if(v * nums[mid] >= target){
                r = mid;
            }else{
                l = mid + 1;
            }
            mid = (l + r) / 2;
        }
        if(v * nums[l] < target)return 0;
        return n - l;
        
        
    }
    vector<int> successfulPairs(vector<int>& spells, vector<int>& potions, long long success) {
         int n = spells.size(); 
         sort(potions.begin(),potions.end());
         vector<int> ans;
         for(int i = 0;i < n;i++){
                ans.emplace_back(findl(potions,spells[i],success));
         }
         return ans;
    }
};
相关推荐
房开民4 小时前
c++总结
java·开发语言·c++
好大哥呀4 小时前
C++ 多态
java·jvm·c++
阿豪学编程5 小时前
LeetCode724.:寻找数组的中心下标
算法·leetcode
墨韵流芳5 小时前
CCF-CSP第41次认证第三题——进程通信
c++·人工智能·算法·机器学习·csp·ccf
hz_zhangrl5 小时前
CCF-GESP 等级考试 2026年3月认证C++五级真题解析
c++·青少年编程·程序设计·gesp·c++五级·gesp2026年3月·gesp c++五级
Σίσυφος19005 小时前
C++ 多肽经典面试题
开发语言·c++·面试
csdn_aspnet6 小时前
C# 求n边凸多边形的对角线数量(Find number of diagonals in n sided convex polygon)
开发语言·算法·c#
禹中一只鱼6 小时前
【力扣热题100学习笔记】 - 哈希
java·学习·leetcode·哈希算法
凌波粒6 小时前
LeetCode--349.两个数组的交集(哈希表)
java·算法·leetcode·散列表
crescent_悦7 小时前
C++:The Largest Generation
java·开发语言·c++