Design and implement a TwoSum class. It should support the following operations: add and find.

add - Add the number to an internal data structure.
find - Find if there exists any pair of numbers which sum is equal to the value.

Example 1:

add(1); add(3); add(5);
find(4) -> true
find(7) -> false

Example 2:

add(3); add(1); add(2);
find(3) -> true
find(6) -> false

题目

设计一个数据结构,能像其中添加数,能查找其中是否存在两数相加等于某值。

Solution1: HashMap

重头戏在find()的实现, 类似two sum的思想:遍历所有的key,同时算出remain = sum - key,  我们的任务是查找

1. key 等于 remain时, 要组成一对pair的条件是map.get(key) >1

2. key不等于remain, 要组成一对pair的条件是,remain也在map中

code

 class TwoSum {  // O(1) add, O(n)find

     private Map<Integer, Integer> map;

     /** Initialize your data structure here. */
public TwoSum() {
map = new HashMap<>();
} /** Add the number to an internal data structure.. */
public void add(int number) {
if(!map.containsKey(number)){
map.put(number, 1);
}else{
map.put(number, map.get(number)+1);
}
} /** Find if there exists any pair of numbers which sum is equal to the value. */
public boolean find(int value) {
for (Integer num : map.keySet()){
int remain = value - num;
if (( num == remain && map.get(num) > 1) || num != remain && map.containsKey(remain)){
24 return true;
}
}
return false;
}
}

注意:

我之前写成

            if(remaining != n){
return map.containsKey(remaining);
}else{
if(map.get(n) > ){
return true;
}
}

一直想不通逻辑上有什么区别。

比如

add(3), add(2), add(1),  find(5)

而此时遍历的key是1, 对应remaining = 4

如果按照错误的思路,程序会直接return map.containsKey(4) -> false

而程序并没有尝试key是3, 对应remaining = 2,  rreturn true 的情况

---------------------------------------------------------------------------

Followup1:

要求O(1) find

思路

1. 在add()操作的时候,就用set做了pre-computation, 来记录 sum for any pair of numbers

2. 如此,在find()操作是,只需要check一下set.contains() 即可

代码

 // O(n) add, O(1) find
public class TwoSumIII {
Map<Integer, Integer> map = new HashMap<>();
Set<Integer> set = new HashSet<>(); public void add(int number) {
// record sum for any pair of numbers
for (Integer n : map.keySet()){
set.add(number + n);
}
// key: each item, value: its frequency
if(!map.containsKey(number)){
map.put(number, 1);
}else{
map.put(number, map.get(number) + 1);
}
}
// set.contains() using O(1) time
public boolean find(int value) {
return set.contains(value);
}
}

[leetcode]170. Two Sum III - Data structure design两数之和III - 数据结构设计的更多相关文章

  1. [LeetCode] 170. Two Sum III - Data structure design 两数之和之三 - 数据结构设计

    Design and implement a TwoSum class. It should support the following operations:add and find. add - ...

  2. 【leetcode】170. Two Sum III - Data structure design 两数之和之三 - 数据结构设计

    Design and implement a TwoSum class. It should support the following operations:  add and find. add  ...

  3. [LeetCode] Two Sum III - Data structure design 两数之和之三 - 数据结构设计

    Design and implement a TwoSum class. It should support the following operations:add and find. add - ...

  4. [LeetCode] Add and Search Word - Data structure design 添加和查找单词-数据结构设计

    Design a data structure that supports the following two operations: void addWord(word) bool search(w ...

  5. LeetCode 170. Two Sum III - Data structure design (两数之和之三 - 数据结构设计)$

    Design and implement a TwoSum class. It should support the following operations: add and find. add - ...

  6. [LeetCode] 211. Add and Search Word - Data structure design 添加和查找单词-数据结构设计

    Design a data structure that supports the following two operations: void addWord(word) bool search(w ...

  7. 【LeetCode】211. Add and Search Word - Data structure design 添加与搜索单词 - 数据结构设计

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 公众号:负雪明烛 本文关键词:Leetcode, 力扣,211,搜索单词,前缀树,字典树 ...

  8. 211 Add and Search Word - Data structure design 添加与搜索单词 - 数据结构设计

    设计一个支持以下两个操作的数据结构:void addWord(word)bool search(word)search(word) 可以搜索文字或正则表达式字符串,字符串只包含字母 . 或 a-z . ...

  9. Leetcode211. Add and Search Word - Data structure design 添加与搜索单词 - 数据结构设计

    设计一个支持以下两种操作的数据结构: void addWord(word) bool search(word) search(word) 可以搜索文字或正则表达式字符串,字符串只包含字母 . 或 a- ...

随机推荐

  1. Oracle使用备忘

    初学Oracle,很多语句记不住,写在这里备忘. 1.查看某表空间的数据文件 select file_name 文件名, tablespace_name 表空间名, bytes 已使用大小M, max ...

  2. 在windows上使用ssh秘钥连接git服务器

    git部署在centos7上 安装好git后,新建一个用户test(注意要加入git用户组)配置ssh秘钥登录,我的另一篇博客有写配置步骤 重点的地方是在windows系统上使用秘钥登录git服务器 ...

  3. C#的发展历程 -- 系列介绍

    C#的发展历程第五 - C# 7开始进入快速迭代道路 C#与C++的发展历程第四 - C#6的新时代 C#与C++的发展历程第三 - C#5.0异步编程巅峰 C#与C++的发展历程第二 - C#4.0 ...

  4. js正则表达式讲的最好的

    https://www.cnblogs.com/chenmeng0818/p/6370819.html

  5. django中多个app放入同一文件夹apps

    开发IDE:pycharm 新建一个apps文件夹 需要整理的app文件夹拖到同一个文件夹中,即apps.(弹出对话框,取消勾选Search for references) 在pycharm 中,右键 ...

  6. Docker之 默认桥接网络与自定义桥接网卡

    docker引擎会默认创建一个docker0网桥,它在内核层连通了其他的物理或虚拟网卡,这就将所有容器和宿主机都放到同一个二层网络. 1. docker如何使用网桥 1.1 Linux虚拟网桥的特点 ...

  7. java 原子性 可见性 有序性

    原子性 原子性是指一个操作或多个操作要么全部执行完成且执行过程不被中断,要么就不执行. 如向变量x赋值操作 x = 10 是原子性的,就不会出现赋值操作进行到一半(x的低16位赋值成功,高16位没有赋 ...

  8. Zookeeper的下载、安装和启动

    一.下载Zookeeper 版本 zookeeper-3.4.13 下载地址:https://archive.apache.org/dist/zookeeper/ 解压后放在/usr/local/zo ...

  9. bootstrap模态框弹框后执行Ajax

    如下: editModal:模态框ID <script> $(document).ready(function() { $('#editModal').on('hidden.bs.moda ...

  10. Linux中加速访问github

    1. 登录http://tool.chinaz.com/dns/ 2. 查询以下域名映射,并分别取访问速度较快的一个ip github.global.ssl.fastly.net   ->    ...