Design and implement a TwoSum class. It should support the following operations:addandfind.

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.

class TwoSum {
    private HashMap<Integer, Integer> nums;

    /** Initialize your data structure here. */
    public TwoSum() {
        nums = new HashMap<>();
    }

    /** Add the number to an internal data structure.. */
    public void add(int number) {
        if(!nums.containsKey(number))
            nums.put(number, 1);
        else
            nums.put(number, nums.get(number) + 1);
    }

    /** Find if there exists any pair of numbers which sum is equal to the value. */
    public boolean find(int value) {
        for(Integer key: nums.keySet()) {
            if(value == 2 * key) {
                if(nums.get(key) > 1)
                    return true;
            } else {
                if(nums.containsKey(value - key))
                    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);
 */

results matching ""

    No results matching ""