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.
For example,
add(1); add(3); add(5);
find(4) -> true
find(7) -> false
这题让设计一个数据结构,和前面几道比起来没难道,只要用好map就行,上代码
class TwoSum { public: void add(int number) { ++m[number];//这里以插入数字为关键词,次数为值 } bool find(int value) { for (auto a : m) {//遍历map的写法,a为m的每个结构的数据对pair int t = value - a.first;//first为关键词,second为值
if ((t != a.first && m.count(t)) || (t == a.first && a.second > 1)) { return true; } } return false; } private: unordered_map<int, int> m; };