LintCode-607: Two Sum III

该题用Array或HashTable都可以。
Array: add()时间复杂度O(n),find()时间复杂度O(n)。
HashTable: add()时间复杂度O(1), find()时间复杂度O(n)。

解法1:Array。add()用类似插入排序。find()用双指针。
代码:

class TwoSum {
public:
    /*
     * @param number: An integer
     * @return: nothing
     */
    void add(int number) {
        nums.push_back(number);
        int i=0, pos=0;
        int len=nums.size();
        //similar to insertion sort
        for (i=0; i<len-1; ++i) {
            if (number<=nums[i]) {
                break;
            }
        }
        pos=i;
        for (i=len-1; i>pos; --i) {
            nums[i]=nums[i-1];
        }
        nums[pos]=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) {
        int p1=0, p2=nums.size()-1;
        while(p1<p2) {
            int sum=nums[p1]+nums[p2];
            if (sum==value) {
                return true;
            } else if (sum>value) {
                p2--;
            } else {
                p1++;
            }
       }
        return false;
    }

    private:
        vector<int> nums;     
};

解法2: HashTable。
代码如下:


class TwoSum {
public:
    void add(int number) {
        unordered_multimap<int, int>::iterator it = dict.find(number);
        if (it == dict.end()) {
            dict.insert(pair<int, int>(number, 1));
        } else {
            it->second++;
        }
    }

 bool find(int value) {
        for (auto h : dict) { //or unordered_multimap<int,int>::iterator it; for (it=dict.begin(); it!=m.end(); it++)
            auto it=dict.find(value-h.first);  //note: h is not pointer, it is a pointer!!!
            if (it != dict.end()) {
                if ((value==(it->first << 1)) && (it->second==1)) continue; //8=4+4 but there is only one 4, then continue. Note: not return false here!
                return true;
            }
        }
        return false;
    }

private:
    unordered_multimap<int, int> dict;    
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值