Leetcode 170 Solution

This article provides solution to leetcode question 170 (two-sum-iii-data-structure-design)

https://leetcode.com/problems/two-sum-iii-data-structure-design

Solution

class TwoSum {
    unordered_map<int, int> m;

public:
    /** Initialize your data structure here. */
    TwoSum() {

    }

    /** Add the number to an internal data structure.. */
    void add(int number) {
        m[number]++;
    }

    /** Find if there exists any pair of numbers which sum is equal to the value. */
    bool find(int value) {
        for (auto it = m.begin(); it != m.end(); it++)
        {
            int other = value - it->first;

            auto it2 = m.find(other);
            if (it2 != m.end() && (it2->second >= 2 || it2 != it))
                return true;
        }

        return false;
    }
};

/**
 * Your TwoSum object will be instantiated and called as such:
 * TwoSum obj = new TwoSum();
 * obj.add(number);
 * bool param_2 = obj.find(value);
 */