170. Two Sum III - Data structure design

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.

Example 1:

add(1); add(3); add(5);
find(4) -> true
find(7) -> false

Example 2:

add(3); add(1); add(2);
find(3) -> true
find(6) -> false

設計時可以考慮到這個class到底是會被大量使用來增加新的num還是搜尋可能的target sum,可分為add-heavy和find-heavy兩種情形,但OJ中find-heavy的code會TLE。

// Add-Heavy
class TwoSum {
public:
    /** Initialize your data structure here. */
    TwoSum() {
        
    }
    
    /** Add the number to an internal data structure.. */
    void add(int number) {
        ++mp[number];
    }
    
    /** Find if there exists any pair of numbers which sum is equal to the value. */
    bool find(int value) {
        for (auto a : mp) {
            int t = value - a.first;
            if ((t != a.first && mp.count(t)) || (t == a.first && mp[t] >= 2))
                return true;
        }
        return false;
    }
private:
    unordered_map<int, int> mp;
};
// Find-Heavy
class TwoSum {
public:
    /** Initialize your data structure here. */
    TwoSum() {
        
    }
    
    /** Add the number to an internal data structure.. */
    void add(int number) {
        if (nums.count(number)) {
            sums.insert(number * 2);
        } else {
            for (auto it = nums.begin(); it != nums.end(); ++it) {
                sums.insert(*it + number);
            }
            nums.insert(number);
        }
    }
    
    /** Find if there exists any pair of numbers which sum is equal to the value. */
    bool find(int value) {
        return sums.count(value);
    }
private:
    unordered_set<int> nums, sums;
};

Last updated

Was this helpful?