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;
    }
};
相关推荐
zhangzhangkeji8 分钟前
c++ 定点 new 及其汇编解释
开发语言·c++
Oracle_66622 分钟前
C基础算法与实现
c语言·算法
Pakho love26 分钟前
Linux:文件与fd(被打开的文件)
android·linux·c语言·c++
W说编程40 分钟前
C语言指针专题四 -- 多级指针
c语言·开发语言·数据结构·c++·嵌入式硬件
我命由我123451 小时前
游戏引擎 Unity - Unity 下载与安装
c语言·开发语言·c++·后端·unity·c#·游戏引擎
h^hh2 小时前
向下调整算法(详解)c++
数据结构·c++·算法
我命由我123452 小时前
游戏引擎 Unity - Unity 启动(下载 Unity Editor、生成 Unity Personal Edition 许可证)
c语言·c++·后端·unity·c#·游戏引擎·ue4
能源革命2 小时前
负荷预测算法模型
算法·能源
海绵波波1072 小时前
350.两个数组的交集 ②
数据结构·算法·leetcode
Evand J3 小时前
基于改进的强跟踪技术的扩展Consider Kalman滤波算法在无人机导航系统中的应用研究
算法·无人机