BiruLyu
5/22/2017 - 5:17 PM

170. Two Sum III - Data structure design.java

public class TwoSum {
    
    private HashMap<Integer, Integer> dict; // using map instead of set is because allowing repetition
    private List<Integer> nums;
    /** Initialize your data structure here. */
    public TwoSum() {
        dict = new HashMap<Integer, Integer>();
        nums = new ArrayList<Integer>();
    }
    
    /** Add the number to an internal data structure.. */
    public void add(int number) {
        if(dict.containsKey(number)){
            dict.put(number, dict.get(number) + 1);
        } else {
            nums.add(number);
            dict.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 i=0; i < nums.size(); i++){
            int num1 = nums.get(i);
            int num2 = value - num1;
            if(num1 == num2 && dict.get(num1) > 1) return true;
            if(num1 != num2 && dict.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);
 */