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;
    }
};
相关推荐
B站计算机毕业设计超人16 分钟前
计算机毕业设计Python+DeepSeek-R1大模型微博舆情分析系统 微博舆情预测 微博爬虫 微博大数 据(源码+LW文档+PPT+详细讲解)
爬虫·python·学习·算法·机器学习·毕业设计·数据可视化
Hann Yang19 分钟前
豆包大模型 MarsCode AI 刷题专栏 001
算法
我想吃余25 分钟前
【初探数据结构】链表OJ算法——快慢指针
数据结构·算法·链表
落羽的落羽35 分钟前
【落羽的落羽 C++】C++入门基础:引用,内联,nullptr
开发语言·c++
濊繵1 小时前
c++进阶--map和set的使用
开发语言·c++
bee-y1 小时前
力扣hot100——多维动态规划
算法·leetcode·动态规划
黑菜钟1 小时前
dp_走方格(包含dfs分析,记忆化搜索)
算法·深度优先
graceyun1 小时前
初阶数据结构(C语言实现)——4.1栈
java·c语言·数据结构
里欧布鲁斯2 小时前
The Wedding Juicer POJ - 2227
算法
攻城狮7号2 小时前
【第20节】C++设计模式(行为模式)-Visitor(访问者)模式
c++·设计模式·访问者模式