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>
class TwoSum
{
HashMap<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)
{
map.put(number, map.getOrDefault(number, 0) + 1);
} /** Find if there exists any pair of numbers which sum is equal to the value. */
public boolean find(int value)
{
for(int num: map.keySet())
{
int target = value - num; if(num == target)
{
if(map.get(num) > 1)
return true;
}
else
{
if(map.containsKey(target))
return true;
}
} return false;
}
} /**
* Your TwoSum object will be instantiated and called as such:
* TwoSum obj = new TwoSum();
* obj.add(number);
* boolean param_2 = obj.find(value);
*/
参考资料:N/A
LeetCode 题目列表 - LeetCode Questions List