当前位置: 首页 > news >正文

LeetCode每日一题,20251008

[咒语和药水的成功对数](https://leetcode.cn/problems/successful-pairs-of-spells-and-potions/description/?envType=daily-question&envId=2025-10-08)
题目介绍,给你两个数据a,b,对于每个a[i],找到b中有多少个数满足a[i] * b[j] >= success

方法一

排序b数组,对于每个a[i],二分出有多少符合条件的b

import java.util.Arrays;public class SolutionBS {public int[] successfulPairs(int[] spells, int[] potions, long success) {int n = spells.length, m = potions.length;int[] res = new int[n];Arrays.sort(potions); // 升序for (int i = 0; i < n; i++) {long need = (success + spells[i] - 1L) / spells[i]; // ceil(success / spells[i])int pos = lowerBound(potions, need);               // [0..m]res[i] = m - pos;                                   // 不需要判断 pos<0}return res;}// 返回第一个 >= target 的下标;若都小于 target,则返回 mprivate int lowerBound(int[] a, long target) {int l = 0, r = a.length;            // 区间不变量:[l, r)while (l < r) {int mid = l + ((r - l) >>> 1);  // 等价于 (l + r) / 2,但避免溢出if ((long)a[mid] >= target) {r = mid;} else {l = mid + 1;}}return l; // l==r}
}

方法二

后缀和,数据量b数组的数字大小为1e5,统计每个数字出现的次数cnt,然后对于每次询问,可以直接找到有多少个数满足

比如 potions=[1,2,2,3,5,5,5],要计算 ≥2 的药水的个数,我们可以统计每个数出现了多少次,记在一个 cnt 数组中。在这个例子中,cnt=[0,1,2,1,0,3],比如 cnt[5]=3 表示 5 出现了 3 次。

class Solution {public int[] successfulPairs(int[] spells, int[] potions, long success) {int mx = 0;for (int y : potions) {mx = Math.max(mx, y);}int[] cnt = new int[mx + 1];for (int y : potions) {cnt[y]++; // 统计每种药水的出现次数}// 计算 cnt 的后缀和for (int i = mx - 1; i >= 0; i--) {cnt[i] += cnt[i + 1];}// 计算完毕后,cnt[i] 就是 potions 值 >= i 的药水个数for (int i = 0; i < spells.length; i++) {long low = (success - 1) / spells[i] + 1;spells[i] = low <= mx ? cnt[(int) low] : 0;}return spells;}
}
http://www.dtcms.com/a/456648.html

相关文章:

  • h5网站建设的具体内容电子商务平台网站模板
  • hive sql优化基础
  • Linux小课堂: Linux 系统的多面性与 CentOS 下载指南
  • 详解redis,MySQL,mongodb以及各自使用场景
  • 开发网站设计公司建设通网站会员共享密码
  • Linux相关工具vim/gcc/g++/gdb/cgdb的使用详解
  • Verilog和FPGA的自学笔记2——点亮LED
  • uniapp创建ts项目tsconfig.json报错的问题
  • Linux性能调优之内核网络栈发包收包认知
  • 静态网站挂马u钙网logo设计影视剪辑
  • Rust 基础语法指南
  • C11 安全字符串转整数函数详解:atoi_s、atol_s、strtol_s 与 strtoimax_s
  • 从入门到实战:全面解析Protobuf的安装配置、语法规范与高级应用——手把手教你用Protobuf实现高效数据序列化与跨语言通信
  • SaaS版MES系统PC端后台功能清单与设计说明
  • 广州建立公司网站多少钱php网站培训机构企业做网站
  • 若依前后端分离版学习笔记(十九)——导入,导出实现流程及图片,文件组件
  • SSM后台投票网站系统9h37l(程序+源码+数据库+调试部署+开发环境)带论文文档1万字以上,文末可获取,系统界面在最后面。
  • 基于springboot高校汉服租赁系统的设计与实现(文末附源码)
  • 【AI大模型】WPS 接入DeepSeek 实战项目详解
  • 12306网站为什么做那么差网站的统计代码是什么意思
  • 第二章 预备知识(线性代数)
  • 建设网站服务器的方式有自营方式山楂树建站公司
  • 10.8 树形dp
  • Java中第三方日志库-Log4J
  • Redis 键(Key)详解
  • 用AI帮忙,开发刷题小程序:软考真经微信小程序API接口文档(更新版)
  • soular入门到实战(5) - Kanass、sward、soular实现sso单点登录
  • 优秀平面设计作品网站wordpress 多人
  • Django5 与 Vue3 表单交互全解析:从基础到实战
  • 《UE5_C++多人TPS完整教程》学习笔记62 ——《P63 多人游戏中的开火特效(Fire Effects in Multiplayer)》