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;
    }
};
相关推荐
乄夜几秒前
嵌入式面试高频(5)!!!C++语言(嵌入式八股文,嵌入式面经)
c语言·c++·单片机·嵌入式硬件·物联网·面试·职场和发展
YYDS31416 分钟前
C++动态规划-01背包
开发语言·c++·动态规划
wydaicls1 小时前
十一.C++ 类 -- 面向对象思想
开发语言·c++
姜君竹1 小时前
QT的工程文件.pro文件
开发语言·c++·qt·系统架构
思捻如枫1 小时前
C++数据结构和算法代码模板总结——算法部分
数据结构·c++
嘉陵妹妹1 小时前
深度优先算法学习
学习·算法·深度优先
GalaxyPokemon2 小时前
LeetCode - 53. 最大子数组和
算法·leetcode·职场和发展
小猫咪怎么会有坏心思呢2 小时前
华为OD机考 - 水仙花数 Ⅰ(2025B卷 100分)
数据结构·链表·华为od
weixin_478689762 小时前
C++ 对 C 的兼容性
java·c语言·c++
k要开心2 小时前
C++概念以及基础框架语法
开发语言·c++