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.
For example,
add(1); add(3); add(5);
find(4) -> true
find(7) -> false
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
class TwoSum{
private:
map<int,int>tbl;
public:
void add(int num)
{
tbl[num] += 1;
}
bool find(int num){
map<int, int>::iterator iter;
for(iter = tbl.begin(); iter != tbl.end(); iter++){
if(num == (iter->first*2) && tbl[iter->first] > 1)return true;
if(tbl.find(tbl[num - iter->first]) != tbl.end())
return true;
}
return false;
}
}
基本思路采用HASH表来存储数据,
add()添加就是加一个元素到HASH表
find(),就是遍历HASH表,逐个判断sum-*iter是否在hash表中