【两次过】Lintcode 607. Two Sum III - Data structure design

设计b并实现一个 TwoSum 类。他需要支持以下操作:add 和 find
add -把这个数添加到内部的数据结构。
find -是否存在任意一对数字之和等于这个值

样例

add(1);add(3);add(5);
find(4)//返回true
find(7)//返回false

解题思路:

    使用unordered_map<int , int> m数据结构,m.first存放数值,m.second存放该数值的次数。

    需要注意的是在判断tmp是否存在于m中时,有tmp与m.first相等和不相等两种情况,不相等直接判断tmp值在m中即可,相等就必须看m.second是否大于1,只有次数大于1才表示存在这个数。

class TwoSum {
public:
    /*
     * @param number: An integer
     * @return: nothing
     */
     
     
    void add(int number) 
    {
        // write your code here
        ++m[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(auto a : m)
        {
            int tmp = value - a.first;
            
            if((m.count(tmp)&&tmp != a.first) || (tmp == a.first&&a.second>1))
                return true;
        }
        return false;
    }
    
private:
    unordered_map<int,int> m;
};


猜你喜欢

转载自blog.csdn.net/majichen95/article/details/80792179
今日推荐