美文网首页
2018-04-16

2018-04-16

作者: aammyytt | 来源:发表于2018-04-16 23:31 被阅读0次

    題目:
    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;
        }
    };
    

    相关文章

      网友评论

          本文标题:2018-04-16

          本文链接:https://www.haomeiwen.com/subject/jkpykftx.html