2018-04-16

題目:
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.

思路:

代碼:

class TwoSum {
public:
    /*
     * @param number: An integer
     * @return: nothing
     */
    multiset<int> nums;
    
    void add(int number) {
        // write your code here
        nums.insert(number);    
    }

    /*
     * @param value: An integer
     * @return: Find if there exists any pair of numbers which sum is equal to the value.
     */
    bool find(int value) {
        // write your code here
        for (int i : nums) {
            int need_count;
            if (i == value-i)
                need_count = 2;
            else
                need_count = 1;
            //如果在裡面找到配對的
            if (nums.count(value - i) >= need_count) {
                return true;
            }
        }
        return false;
    }
};
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,448评论 0 10
  • 是谁 把春天妖娆的柳枝 在秋天 梳成了粗粗的辫子 是谁 在朦胧的清晨 淡蓝的天际 挥舞出长长的云袖 是谁 躲在高楼...
    风儿轻轻阅读 283评论 1 5
  • 上班第六天,虽然心劲很足,虽然才工作了没几天,但还是感觉累,这种累从原来的心理上的变成了身体上的,虽然还是持续...
    六月霓裳阅读 712评论 0 2
  • 这段时间,让我对后台产品有了初步的了解。所以想尝试自己总结一下对后台产品设计和开发的一些知识。后台产品也有不同的分...
    会飞的虾仁阅读 636评论 1 19