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

1865.找出和为指定值得下标对

为了找出满足指定值得下标对,可以假设nums1[i]的值为num,从而tot-num就是要从nums2中找的的,可以事先维护一个哈希表,从而直接获取tot-num的出现次数。

class FindSumPairs {int[] nums1;int[] nums2;// nums2的长度很长Map<Integer, Integer> freq; // 用于统计nums2中各数字出现的频率public FindSumPairs(int[] nums1, int[] nums2) {// 初始化对象this.nums1 = nums1;this.nums2 = nums2;this.freq = new HashMap<>();// 初始化for (int num : nums2){freq.put(num, freq.getOrDefault(num, 0) + 1);}}public void add(int index, int val) {// 将val加到nums2[index]的值上// 可以直接按照索引进行操作,// 但是维护了频率表,因此需要先对频率表进行更新int oldValue = nums2[index];// 减少oldValue的频率freq.put(oldValue, freq.get(oldValue) - 1);// 如果减到0,则去掉if (freq.get(oldValue) == 0){freq.remove(oldValue);}// 更新nums2[index] += val;// 更新freqint newValue = nums2[index];freq.put(newValue, freq.getOrDefault(newValue, 0)+1);}public int count(int tot) {// 返回满足条件的nums1[i]+nums2[j]=tot下标对数量// 注意时间复杂度// 利用freq进行统计int res = 0;for (int num : nums1){// 余数int complement = tot - num;res += freq.getOrDefault(complement, 0);}return res;}
}/*** Your FindSumPairs object will be instantiated and called as such:* FindSumPairs obj = new FindSumPairs(nums1, nums2);* obj.add(index,val);* int param_2 = obj.count(tot);*/
http://www.dtcms.com/a/268419.html

相关文章:

  • Java笔记-下
  • MyBatis-Plus分页拦截器原理深度解析
  • new与malloc[c++面试系列]
  • GCC/G++编译器详解:从编译原理到动静态链接
  • 2025 JuniorCryptCTF re 部分wp
  • 【一起来学AI大模型】算法核心:数组/哈希表/树/排序/动态规划(LeetCode精练)
  • 【Docker基础】Docker数据卷管理:docker volume rm与prune命令对比
  • 计算机网络实验——配置ACL
  • vue3 当前页面方法暴露
  • 「Java题库」基础程序设计(理论+操作)
  • Excel 日期计算与最小日期选择(附示例下载)
  • DAY 49
  • monorepo + Turborepo --- 开发应用程序
  • Go语言实现双Token登录的思路与实现
  • 微服务基础:Spring Cloud Alibaba 组件有哪些?
  • 随机森林算法详解:Bagging思想的代表算法
  • 自存bro code java course 笔记(2025 及 2020)
  • 【Linux网络编程】Socket - UDP
  • CppCon 2018 学习:What do you mean “thread-safe“
  • Linux操作系统之文件(五):文件系统(下)
  • 数据库|达梦DM数据库安装步骤
  • 谷歌浏览器安全输入控件-allWebSafeInput控件
  • 黑布淡入淡出效果
  • Vue2 day07
  • STM32两种不同的链接配置方式
  • Python 中 ffmpeg-python 库的详细使用
  • CppCon 2018 学习:Undefined Behavior is Not an Error
  • Solidity——pure 不消耗gas的情况、call和sendTransaction区别
  • 【PyTorch】PyTorch中torch.nn模块的池化层
  • 汇编与接口技术:8259中断实验