[leetcode]Two Sum III - Data structure design

2058 ワード

hashtableで記録する
 
class TwoSum {
public:
    void add(int number) {
        rec[number]++;
    }

    bool find(int value) {
        for (auto it = rec.begin(); it != rec.end(); it++) {
            int val = value - it->first;
            if (val == it->first) {
                if (it -> second > 1) return true;
            } else {
                if (rec.find(val) != rec.end()) {
                    return true;
                }
            }
        }
        return false;
    }
private:
    unordered_map<int, int> rec;
};