Two Sum III - Data structure design
add(1); add(3); add(5);
find(4) -> true
find(7) -> falseadd(3); add(1); add(2);
find(3) -> true
find(6) -> falseAnalysis
Solution
Last updated
add(1); add(3); add(5);
find(4) -> true
find(7) -> falseadd(3); add(1); add(2);
find(3) -> true
find(6) -> falseLast updated
class TwoSum {
private 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 (Map.Entry<Integer, Integer> entry : map.entrySet()) {
int num1 = entry.getKey();
int num2 = value - num1;
if ((num1 == num2 && map.get(num2) > 1) || (num1 != num2 && map.containsKey(num2))) {
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);
*/class TwoSum {
Map<Integer,Boolean> map;
List<Integer> list;
int low = Integer.MAX_VALUE;
int high = Integer.MIN_VALUE;
/** Initialize your data structure here. */
public TwoSum() {
map = new HashMap<>();
list = new LinkedList<>();
}
/** Add the number to an internal data structure.. */
public void add(int number) {
if(map.containsKey(number)){
map.put(number,true);
}else{
map.put(number,false);
list.add(number);
low = Math.min(low,number);
high = Math.max(high,number);
}
}
/** Find if there exists any pair of numbers which sum is equal to the value. */
public boolean find(int value) {
if(value < 2* low || value > 2*high) return false;
for(int num : list){
int target = value - num;
if(map.containsKey(target)){
if(num != target) return true;
else if(map.get(target)) return true;
}
}
return false;
}
}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);
}
}