Python - Hashmap Approach - O(n)


  • 0
    J

    Use dictionary to store the numbers and their count. For each key, check if the target value - key is also present in dictionary.

    class TwoSum:
    
        def __init__(self):
            """
            Initialize your data structure here.
            """
            self.dict = dict()
            
    
        def add(self, number):
            """
            Add the number to an internal data structure..
            :type number: int
            :rtype: void
            """
            if self.dict.__contains__(number) == True:
                self.dict[number] += 1
            else:
                self.dict[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 key in self.dict.keys():
                num = value - key
                if self.dict.__contains__(num) == True:
                    if num == key and self.dict[key] > 1:
                        return True
                    if key != num:
                        return True
            return False
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.