170. Two Sum III - Data structure design

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 map;
    
    TwoSum() {
        map = new HashMap();
    }
    // 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 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 sum;
    Set num;
        
    TwoSum(){
        sum = new HashSet();
        num = new HashSet();
    }
    // Add the number to an internal data structure.
    public void add(int number) {
        if(num.contains(number)) {
            sum.add(number * 2);
        } else {
            Iterator 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);
    }
}

你可能感兴趣的:(170. Two Sum III - Data structure design)