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;
            //如果在裡面找到配對(duì)的
            if (nums.count(value - i) >= need_count) {
                return true;
            }
        }
        return false;
    }
};
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi閱讀 7,861評(píng)論 0 10
  • 是誰 把春天妖嬈的柳枝 在秋天 梳成了粗粗的辮子 是誰 在朦朧的清晨 淡藍(lán)的天際 揮舞出長(zhǎng)長(zhǎng)的云袖 是誰 躲在高樓...
    風(fēng)兒輕輕閱讀 322評(píng)論 1 5
  • 上班第六天,雖然心勁很足,雖然才工作了沒幾天,但還是感覺累,這種累從原來的心理上的變成了身體上的,雖然還是持續(xù)...
    六月霓裳閱讀 838評(píng)論 0 2
  • 這段時(shí)間,讓我對(duì)后臺(tái)產(chǎn)品有了初步的了解。所以想嘗試自己總結(jié)一下對(duì)后臺(tái)產(chǎn)品設(shè)計(jì)和開發(fā)的一些知識(shí)。后臺(tái)產(chǎn)品也有不同的分...
    會(huì)飛的蝦仁閱讀 668評(píng)論 1 19

友情鏈接更多精彩內(nèi)容