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
Solution1:Hashtable find再去遍历找
Add O(1) find O(N)
Solution2:Hashset add先遍历算好sum
Add O(N) find O(1)
Solution1 Code:
public class TwoSum {
Map<Integer,Integer> map;
TwoSum() {
map = new HashMap<Integer,Integer>();
}
// Add the number to an internal data structure.
public void add(int number) {
if(map.containsKey(number)) {
map.put(number, 2);
}else {
map.put(number, 1);
}
}
// Find if there exists any pair of numbers which sum is equal to the value.
public boolean find(int value) {
Iterator<Integer> iter = map.keySet().iterator();
while(iter.hasNext()) {
int num1 = iter.next();
int num2 = value - num1;
if(map.containsKey(num2)){
if(num1 != num2 || map.get(num2) == 2){
return true;
}
}
}
return false;
}
}
Solution2 Code:
public class TwoSum {
Set<Integer> sum;
Set<Integer> num;
TwoSum(){
sum = new HashSet<Integer>();
num = new HashSet<Integer>();
}
// Add the number to an internal data structure.
public void add(int number) {
if(num.contains(number)) {
sum.add(number * 2);
} else {
Iterator<Integer> iter = num.iterator();
while(iter.hasNext()){
sum.add(iter.next() + number);
}
num.add(number);
}
}
// Find if there exists any pair of numbers which sum is equal to the value.
public boolean find(int value) {
return sum.contains(value);
}
}