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. CNN+BLSTM+CTC的验证码识别从训练到部署

    项目地址:https://github.com/kerlomz/captcha_trainer 1. 前言 本项目适用于Python3.6,GPU>=NVIDIA GTX1050Ti,原mast ...

  2. 谈谈 ServerFul 架构

    我写了一篇文章 <自己实现一个线程池>  https://www.cnblogs.com/KSongKing/p/9803935.html , 其实 不仅仅 是 线程池, 中间件 层 的 ...

  3. Guava 1:概览

    一.引言 都说java是开源的,但是除了JDK外,能坚持更新且被广泛认可的开源jar包实在是不可多得.其中最显眼的自然是guava了,背靠google自然底气十足,今天就来解开guava的面纱,初探一 ...

  4. [转]使用python爬取东方财富网机构调研数据

    最近有一个需求,需要爬取东方财富网的机构调研数据.数据所在的网页地址为: 机构调研 网页如下所示: 可见数据共有8464页,此处不能直接使用scrapy爬虫进行爬取,因为点击下一页时,浏览器只是发起了 ...

  5. Python完全新手教程

    转发:作者: taowen  来源: 博客园  发布时间: 2010-10-01 00:42  阅读: 1618 次  推荐: 0                  原文链接  [收藏] Lesson ...

  6. VS2017 对com组件调用返回错误hresult e_fail

    解决步骤如下: 第一步: 第二步:进入VS2017 安装目录,如下(路径仅供参考) 执行:gacutil -i Microsoft.VisualStudio.Shell.Interop.11.0.dl ...

  7. instant client 的配置

    instant client 的配置 oracle server developer自带了客户端 解压目录:D:\Toolkit\instantclient_11_2 设置环境变量 Ø  在Path变 ...

  8. MySql开启远程账户登陆总结

    1.更改 "mysql" 数据库里的 "user" 表里的 "host" 项,从"127.0.0.1"改成"% ...

  9. [蓝桥杯]ALGO-188.算法训练_P0504

    Anagrams指的是具有如下特性的两个单词:在这两个单词当中,每一个英文字母(不区分大小写)所出现的次数都是相同的.例如,Unclear和Nuclear.Rimon和MinOR都是Anagrams. ...

  10. Java中用字符串常量赋值和使用new构造String对象的区别

    String str1 = "ABC"; String str2 = new String("ABC"); String str1 = “ABC”;可能创建一个 ...