[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:
For example,
思路: 用hash表将元素都保存起来,然后查找的时候遍历hash表, 看当前元素与要查找的元素是否存在hash表中.
本题一个主要的问题就是有可能有重复元素, 即如果要查找的值如6, 可能由3+3构成, 这样如果你只有一个3是无法构成6的, 因此要对元素的个数进行记录并判断.
代码如下:
Design and implement a TwoSum class. It should support the following operations:
addand
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);
相关文章推荐
- Unix Network Programming1
- Mycat 月分片方法 - pursuer.chen - 博客园
- python代码风格-PEP8
- lintcode-medium-3 Sum Closest
- Rain
- ASUS TR-N14U固件中继小白教程
- L18函數:靈活即強大
- json-schema-core(liuhailong翻译)
- lintcode-medium-3 Sum
- [leetcode] 288. Unique Word Abbreviation 解题报告
- 获取、增加、修改、删除sqlserver字段描述及快速查看表字段与描述
- docker+node+Cordova 多平台流媒体直播系统 一 centos6.5 源码编译安装node5.8(1)
- #001 为知笔记,测试发布到博客园
- 63.队列:1. 寻找经过结点最少的路径
- 63.队列:1. 寻找经过结点最少的路径
- 63.队列:1. 寻找经过结点最少的路径
- 63.队列:1. 寻找经过结点最少的路径
- [leetcode] 276. Paint Fence 解题报告
- 扫扫土,开工啦~
- Android ImageSlider实现广告轮播