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;
    }
};
相关推荐
forest_091 小时前
多 Agent 协作第二课:交叉验证≠独立验证
人工智能·python·算法·机器学习·prompt·agi
九英里路1 小时前
protobuf快速上手
网络·c++·中间件·json·谷歌·序列化·protobuf
纪念 2292 小时前
C++ 算法基础 (差分)
开发语言·c++·算法
文丑颜不良啊5 小时前
LeetCode2761~2780题目解析
java·leetcode
jyOverQ5 小时前
从零学 JVM(六):垃圾回收算法详解——标记清除、标记复制与标记整理
jvm·算法
ShineWinsu7 小时前
对于Qt:QTreeWidget常见属性以及QTreeWidgetItem类的解析
开发语言·c++·qt·gui·客户端·多叉树·qtreewidget
严肃小白兔7 小时前
第 06/24 期:神经网络的反向传播算法:从链式法则到梯度计算
人工智能·神经网络·算法
落羽的落羽7 小时前
【C++】C++17的主要特性
linux·服务器·开发语言·c++·算法·机器学习
文丑颜不良啊7 小时前
LeetCode2841~2860题目解析
java·leetcode