C++ two-pointes solution (easy way to handle duplicaiton).

  • 21
    vector<vector<int>> threeSum(vector<int>& nums) {
        sort(nums.begin(), nums.end());
        vector<vector<int>> res;
        for (unsigned int i=0; i<nums.size(); i++) {
            if ((i>0) && (nums[i]==nums[i-1]))
            int l = i+1, r = nums.size()-1;
            while (l<r) {
                int s = nums[i]+nums[l]+nums[r];
                if (s>0) r--;
                else if (s<0) l++;
                else {
                    res.push_back(vector<int> {nums[i], nums[l], nums[r]});
                    while (nums[l]==nums[l+1]) l++;
                    while (nums[r]==nums[r-1]) r--;
                    l++; r--;
        return res;

  • 0
    This post is deleted!

  • 8

    In fact, there are two out-of-range bugs in the above code (see the last two whiles). You'd better write it like this:

    while (l + 1 < k && nums[l]==nums[l+1]) l++;
    while (r - 1 > l && nums[r]==nums[r-1]) r--;

  • 0

    Very smart method.I like it.

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.