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这道题是让我们来设计一个数据结构,而其中两个功能一个是添加元素,一个是找到是否存在其中两个元素的值相加等于给定的target,这道题其实就是two sum的一个变种,我当时做two sum直接用了hashset,然后只需要找是否存在target减去当前值是否存在于hashset中即可。但这道题有些不一样在于可能添加相同的数,这样的情况就会导致,如果一个target是当前数的两倍,如果这个数只出现一次那么肯定返回false,如果出现两次那么就要返回true了,所以我们除了要记录存在哪些值,还需要记录他们出现的次数。这样的话hashmap就成为了我们的首选。和two sum的区别在于需要判断一个条件,即如果某个key值是target的一半,那么检查他出现的次数,如果是两次及以上,返回true,如果只有一次,就返回false
public class TwoSum {
private HashMap<Integer,Integer> res;
//Initialization
public TwoSum(){
res= new HashMap<Integer,Integer>();
}
// Add the number to an internal data structure.
public void add(int number) {
if(res.containsKey(number)){
int temp = res.get(number);
res.put(number,temp+1);
}else{
res.put(number,1);
}
}
// Find if there exists any pair of numbers which sum is equal to the value.
public boolean find(int value) {
for(int a:res.keySet()){
int temp = value-a;
//check whether there exists the difference between target and current value in the map
if(res.containsKey(temp)&&temp!=a){
return true;
}else if(temp==a&&res.get(a)>1){
return true;
}
}
return false;
}
}
// Your TwoSum object will be instantiated and called as such:
// TwoSum twoSum = new TwoSum();
// twoSum.add(number);
// twoSum.find(value);