您的位置:首页 > 其它

[leetcode] 170. Two Sum III - Data structure design 解题报告

2016-03-12 07:21 351 查看
题目链接:https://leetcode.com/problems/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


思路: 用hash表将元素都保存起来,然后查找的时候遍历hash表, 看当前元素与要查找的元素是否存在hash表中.

本题一个主要的问题就是有可能有重复元素, 即如果要查找的值如6, 可能由3+3构成, 这样如果你只有一个3是无法构成6的, 因此要对元素的个数进行记录并判断.

代码如下:

class TwoSum {
public:

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

// Find if there exists any pair of numbers which sum is equal to the value.
bool find(int value) {
for(auto val: hash)
{
if(value!=2*val.first && hash.count(value-val.first))
return true;
if(value==2*val.first && val.second > 1)
return true;
}
return false;
}
private:
unordered_map<int, int> hash;
};

// Your TwoSum object will be instantiated and called as such:
// TwoSum twoSum;
// twoSum.add(number);
// twoSum.find(value);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: