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

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) -> true
find(7) -> false

 


 题目标签:Hash Table

  题目让我们设计一个 两数之和的 class, 要有add(number) 和 find(value)功能。

  建立HashMap,number 当作 key;number 出现的次数当作 value保存。

  要注意的是,两数之和的 两数可以是相同的数字,出现两次。比如 2 + 2 = 4 也是可以的。

 

 

Java Solution:

Runtime beats 82.39% 

完成日期:05/16/2017

关键词:HashMap

关键点:HashMap<number, occurrence>

 1 class TwoSum 
 2 {
 3     HashMap<Integer, Integer> map;
 4     /** Initialize your data structure here. */
 5     public TwoSum() 
 6     {
 7         map = new HashMap<>();
 8     }
 9     
10     /** Add the number to an internal data structure.. */
11     public void add(int number) 
12     {
13         map.put(number, map.getOrDefault(number, 0) + 1);
14     }
15     
16     /** Find if there exists any pair of numbers which sum is equal to the value. */
17     public boolean find(int value) 
18     {
19         for(int num: map.keySet())
20         {
21             int target = value - num;
22             
23             if(num == target)
24             {
25                 if(map.get(num) > 1)
26                     return true;
27             }
28             else
29             {
30                 if(map.containsKey(target))
31                     return true;
32             }
33         }
34         
35         return false;
36     }
37 }
38 
39 /**
40  * Your TwoSum object will be instantiated and called as such:
41  * TwoSum obj = new TwoSum();
42  * obj.add(number);
43  * boolean param_2 = obj.find(value);
44  */

参考资料:N/A

 

LeetCode 题目列表 - LeetCode Questions List

posted @ 2017-10-26 04:47  Jimmy_Cheng  阅读(369)  评论(0编辑  收藏  举报