Difficulty:easy

 More:【目录】LeetCode Java实现

Description

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

Intuition

add(input): Use HashMap to store the input as key and its count as value.

find(value): similar to Two Sum

Solution

import java.util.HashMap;
import java.util.Map; public class TwoSum { HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(); public void add(int input) {
if (map.containsKey(input)) {
map.put(input, map.get(input) + 1);
} else
map.put(input, 1);
} public boolean find(int sum) {
for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
if (map.containsKey(sum - entry.getKey())) {
if (entry.getKey() == sum - entry.getKey() && entry.getValue() == 1)
return false;
return true;
}
}
return false;
} public static void main(String[] args) {
TwoSum a = new TwoSum();
a.add(2);
System.out.println(a.find(4)==false);
a.add(2);
a.add(6);
System.out.println(a.find(4)==true);
System.out.println(a.find(12)==false);
System.out.println(a.find(8)==true);
System.out.println(a.find(2)==false);
a.add(10);
System.out.println(a.find(12)==true);
}
}

  

true
true
true
true
true
true

TwoSum

Complexity

Time complexity :

For Method add(): O(1) 

For Method find(): O(n)   (not O(1), because we need to iterate through the hashMap)

Space complexity : 

O(n)  for storage

What I've learned

1. Be aware of the duplicates when writing the method find().

2. How to iterate through an HashMap? Refer to 遍历HashMap

 More:【目录】LeetCode Java实现

最新文章

  1. Android中用TextView显示大量文字的方法
  2. 动词 or 名词 :这是一个问题 【转载】
  3. 关于BaseAdapter的使用及优化心得(一)
  4. post请求json内容丢失问题
  5. STM32F10x 学习笔记6(USART实现串口通讯 2)
  6. phpcms v9教程 联动搜索在房地产网站开发中的应用
  7. java代理的深入浅出(二)-CGLIB
  8. Java基础—String类小结
  9. jfinal编码问题及解决
  10. django 项目中遇到的问题(持续更新中)
  11. C/C++结构体成员偏移量获取
  12. 【vue】vue +element 搭建项目,点击空白处关闭弹窗
  13. mysql查询表达式解析
  14. List集合remove元素的问题
  15. Android Animatioin总结
  16. nginx 4层tcp代理获取真实ip
  17. 阿里云slb+https 实践操作练习
  18. java基础学习总结——static关键字
  19. locate 命令(转)
  20. 树的各种操作java

热门文章

  1. NOIP2018退役总结
  2. 洛谷 P2376 [USACO09OCT]津贴Allowance 解题报告
  3. 面试题:get和post的本质区别
  4. PostgreSQL——前言
  5. 异步IO的并发能力:backlog的配置很重要
  6. Mac OS X下:TensorBoard可视化问题
  7. requestMapping之地址映射
  8. python爬虫 scrapy3_ 安装指南
  9. 命令卸载ie11
  10. Hadoop上传文件时报错: could only be replicated to 0 nodes instead of minReplication (=1)....