博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
170. Two Sum III - Data structure design
阅读量:4678 次
发布时间:2019-06-09

本文共 2420 字,大约阅读时间需要 8 分钟。

题目:

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.

For example,

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

链接: 

题解:

设计two sum,这道题用hashmap很适合,加入是O(1),查找的话要遍历整个keyset,所以是O(n)。

Time Complexity - O(n) , Space Complexity - O(n)

public class TwoSum {    Map
map = new HashMap<>(); public void add(int number) { if(map.containsKey(number)) map.put(number, map.get(number) + 1); else map.put(number, 1); } public boolean find(int value) { for(int i : map.keySet()) { int res = value - i; if(map.containsKey(res)) { if(res == i && map.get(i) >= 2 ) return true; if(res != i) return true; } } return false; }}

 

二刷:

使用了与一刷一样的方法,这样看起来比较慢,要改进。 

好好研究了一下discuss,发现了几个问题

  1. 遍历整个map的时候,用entrySet比keySet快
  2. 可以建一个set保存之前查询过并且找到答案的value
  3. 使用ArrayList来保存之前加入过的数字,再遍历这个ArrayList比遍历HashMap的keySet和entrySet都要快很多...

Java:

Time Complexity - O(n) , Space Complexity - O(n)

public class TwoSum {    Map
map = new HashMap<>(); Set
valueSet; public TwoSum() { map = new HashMap<>(); valueSet = new HashSet<>(); } // 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, 2); } } // Find if there exists any pair of numbers which sum is equal to the value. public boolean find(int value) { if (valueSet.contains(value)) { return true; } for (int i : map.keySet()) { int remain = value - i; if (map.containsKey(remain)) { if ((remain == i && map.get(remain) > 1) || remain != i) { valueSet.add(value); return true; } } } return false; }}// Your TwoSum object will be instantiated and called as such:// TwoSum twoSum = new TwoSum();// twoSum.add(number);// twoSum.find(value);

 

Reference:

https://leetcode.com/discuss/76823/beats-100%25-java-code

转载于:https://www.cnblogs.com/yrbbest/p/4491638.html

你可能感兴趣的文章
【分享】从《水浒传》中反思什么是真正的执行力
查看>>
java中的static
查看>>
5.侧边栏逻辑
查看>>
评论博客
查看>>
用户代理字符串识别工具源码与slf4j日志使用
查看>>
算法导论第6部分图算法,第22章图的基本算法
查看>>
提示框第三方库之MBProgressHUD
查看>>
C语言 10-字符和字符串常用处理函数
查看>>
C++ 表达式语句 海伦的故事
查看>>
32位汇编学习笔记(1)
查看>>
day_01
查看>>
2013年12月日本語能力試験N3聴解部分
查看>>
uva 1349(拆点+最小费用流)
查看>>
关于SessionFactory的不同实现类分别通过getCurrentSession()方法 和 openSession() 方法获取的Session对象在保存对象时的一些区别...
查看>>
Web开发细节搜集
查看>>
织梦kindeditor图片上传增加图片说明alt属性和title属性
查看>>
HTML fieldset标签
查看>>
Qt 之 饼图
查看>>
算法总结系列之二: 快速排序(QuickSort)
查看>>
会放弃的人生才会更洒脱
查看>>