Skip to content

Latest commit

 

History

History
36 lines (31 loc) · 903 Bytes

170.-two-sum-iii-data-structure-design.md

File metadata and controls

36 lines (31 loc) · 903 Bytes

170. Two Sum III - Data Structure Design

class TwoSum:
    """
    @param number: An integer
    @return: nothing
    """
    def __init__(self):
        from collections import defaultdict
        self.cache = defaultdict(int)
    
    def add(self, number):
        # write your code here
        ## add(5) >>> self.cache {5:0} 
        self.cache[number] += 1

    """
    @param value: An integer
    @return: Find if there exists any pair of numbers which sum is equal to the value.
    """
    def find(self, value):
        # write your code here
        ## 最难就是两个一样
        for k in self.cache.keys(): 
            if k == value-k:
                if self.cache.get(value-k) > 1:
                    return True
            else :
                if self.cache.get(value-k):
                    return True
        return False
    
    # 插入0(1),查找O(N)