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

【LeetCode 0170】【哈希】两数之和(3) 数据结构设计

https://leetcode.com/problems/two-sum-iii-data-structure-design/

描述

Design and implement a TwoSum class. It should support the following operations: add and find.
add(input) – Add the number input to an internal data structure.
find(value) – Find if there exists any pair of numbers which sum is equal to the value.
For example

add(1); add(3); add(5); 
find(4) // true; 
find(7) // false
题解
  • 暴力法(哈希+数组):计算每一对数字之和放入hashmap,O(n2)个存储空间,同时需要记住已经加入的N个数字,add时,需要与每个已加入的数字做加法存入hashmap,find时,只需要O(1)时间复杂度
  • 二分插入+双指针:保持已经插入的数字有序,add时查找插入位置插入,find时使用双指针O(n)时间复杂度
  • 高效哈希法,只需要存储所有插入的数字,为插入数据为key,次数为value(注意哈希中存在多个相同的数字)
function TwoSum(){this.hashmap = {};
}
TwoSum.prototype.add = function(e){if(null == this.hashmap[e]){this.hashmap[e] = 1;}else{this.hashmap[e] ++;}
}
TwoSum.prototype.find = function(sum){for(let current in this.hashmap){let antoher = sum-current ;if(antoher == current && this.hashmap[current] > 1){//存在 多个相同的valuesreturn true;}else if(null != this.hashmap[antoher]){// 存在不同的2个数字之和为sumreturn true}}return false
}
http://www.lryc.cn/news/250916.html

相关文章:

  • 005、简单页面-容器组件
  • stm32中断调用流程
  • 18487.1 - 2015 电动汽车充电系统标准 第1部分 关键点梳理
  • WPF实战项目十八(客户端):添加新增、查询、编辑功能
  • 职位招聘管理与推荐系统Python+Django网页界面+协同过滤推荐算法
  • C#文件流二进制文件的读写
  • 如何正确选择爬虫采集接口和API?区别在哪里?
  • k8s部署jenkins
  • HTTP相关
  • Armv8.x和Armv9.x架构扩展简介
  • node的proxy-server使用
  • FO-like Transformation in QROM Oracle Cloning
  • Redis - 多数据源切换
  • 采集工具-免费采集器下载
  • 使用MD5当做文件的唯一标识,这样安全么?
  • 【算法通关村】链表基础经典问题解析
  • 【华为OD题库-056】矩阵元素的边界值-java
  • zabbix_sender——向zabbix交互的sdk
  • JDBC概述(什么是JDBC?JDBC的原理、Mysql和Sql Server入门JDBC操作)
  • 【android开发-06】android中textview,button和edittext控件的用法介绍
  • 【JMeter】BeanShell了解基础知识
  • Unity | 渡鸦避难所-0 | 创建 URP 项目并导入商店资源
  • SQL Server数据库部署
  • YOLOv8界面-目标检测+语义分割+追踪+姿态识别(姿态估计)+界面DeepSort/ByteTrack-PyQt-GUI
  • MiniDumpWriteDump函数生成dmp文件
  • 【Qt开发流程】之事件系统1:事件系统描述及事件发生流程
  • 初始数据结构(加深对旋转的理解)
  • Android 13 - Media框架(18)- CodecBase
  • 关于微信公众号授权的几件事
  • Docker监控Weave Scope的安装和使用