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

【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){
	   		//存在 多个相同的values
            return true;
	   }else if(null != this.hashmap[antoher]){
	   	   // 存在不同的2个数字之和为sum
	   	   return true
	   }
    }
    return false
}

http://www.kler.cn/news/159943.html

相关文章:

  • Unity 加载本地或网络图片并转为精灵(Sprite)的方法
  • java WebSocket带参数处理使用
  • 逆向爬虫进阶实战:突破反爬虫机制,实现数据抓取
  • UEC++ 探索虚幻5笔记(捡金币案例) day12
  • Webgis学习总结
  • 数据增强改进,实现检测目标copypaste,增加目标数据量,提升精度
  • 安全行业招聘信息汇总
  • 浅谈Elasticsearch安全和权限管理
  • Ubuntu下应用软件安装
  • c语言函数与指针
  • Redis 入门、基础。(五种基本类型使用场景)
  • 8、Broker进一步了解
  • OracleRac跨网段修改Public IP/VIP/Private IP/Scan IP
  • c语言经典题目
  • Distilling the Knowledge in a Neural Network(2015.5)(d补)
  • ElasticSearch篇---第三篇
  • Leetcode—383.赎金信【简单】
  • Spring Cloud Gateway与spring-cloud-circuitbreaker集成与理解
  • 【IC前端虚拟项目】git和svn项目托管平台的简单使用说明
  • LeetCode Hot100 200.岛屿数量
  • Hadoop学习笔记(HDP)-Part.03 资源规划
  • 【Pytorch使用自制数据集,Dataloader】
  • 7.上传project到服务器及拉取服务器project到本地、更新代码冲突解决
  • Leetcode每日一题学习训练——Python3版(最小化旅行的价格总和)
  • Mac-idea快捷键操作
  • Android 横竖屏切换 窗口全屏
  • C++ 构造函数与析构函数
  • Python Flask 框架开发
  • K-Radar:适用于各种天气条件的自动驾驶4D雷达物体检测
  • 图形遍历效率低?试试 R 树