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);
}
}