Two Sum Data structure

Question

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.

Thoughts

The original two sum problem is solved by hashmap, actually here we can directly use a hashmap to store the numbers

Solution

class TwoSum(object):

    def __init__(self):
        """
        initialize your data structure here
        """
        self.nums = {}

    def add(self, number):
        """
        Add the number to an internal data structure.
        :rtype: nothing
        """
        if number in self.nums:
            self.nums[number] += 1
        else:
            self.nums[number] = 1

    def find(self, value):
        """
        Find if there exists any pair of numbers which sum is equal to the value.
        :type value: int
        :rtype: bool
        """

        for i in self.nums:
            b = value - i
            if b in self.nums and (b != i or self.nums[i] > 1):
                return True
        return False


# Your TwoSum object will be instantiated and called as such:
# twoSum = TwoSum()
# twoSum.add(number)
# twoSum.find(value)