Tony's Log

Algorithms, Distributed System, Machine Learning

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

Now that you've solved 2sum, 3sum can be easily converted as 2sum.

Also please note the while loops for i1 and i2: they are to make sure no duplicates.

class Solution {
public:
    vector<vector<int> > threeSum(vector<int> &num) {
        vector<vector<int> > ret;
        if (num.size() < 3) return ret;

        std::sort(num.begin(), num.end());

        for (int i0 = 0; i0 < num.size() - 2; i0++)
        {
            if (i0 > 0 && num[i0] == num[i0 - 1]) continue;

            int tgt = -num[i0];
            int i1 = i0 + 1, i2 = num.size() - 1;

            while (i1 < i2)
            {
                int curr = num[i1] + num[i2];
                if (curr == tgt)
                {
                    vector<int> rt;
                    rt.push_back(num[i0]);
                    rt.push_back(num[i1]);
                    rt.push_back(num[i2]);
                    ret.push_back(rt);
                    while (++i1, num[i1] == num[i1-1]);
                }
                else if (curr < tgt)
                {
                    while (++i1, num[i1] == num[i1-1]);
                }
                else if (curr > tgt)
                {
                    while (--i2, num[i2] == num[i2 + 1]);
                }
            }
        }

        return ret;
    }
};
posted on 2014-08-18 10:12  Tonix  阅读(149)  评论(0编辑  收藏  举报