3Sum

Given an array S of n integers, are there elements abc in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.

Note:

  • Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c)
  • The solution set must not contain duplicate triplets.

    For example, given array S = {-1 0 1 2 -1 -4},

    A solution set is:
    (-1, 0, 1)
    (-1, -1, 2)
這道題和TwoSum的思路一致,利用雙指針,雙向向中間靠攏。依據題目的意思,首先要保證組合結果有序,所以首先應該對nums排序,其次是,對於nums[i]中的每一個數,在[i + 1, high]的範圍內,找兩個數,使其和爲0 - nums[i], 這一步應該用到Two,但要做修改去重,去重的依據是,相同的數只要計算一次,不能多次計算。題目的重點應該就是在如何去重上。
class Solution {
public:
    //類似於Two Sum,對於每一個給定的nums[i],查找是否存在另外的兩個數,使得 nums[i] + nums[j] + nums[k] = 0;
    //因爲最後的結果要有序,所以先對nums排序,使其有序;題目的關鍵點是如何避免重複計算,即避免出現重複的(a, b, c)
    //這不但可以達到輸出的要求,還可以減少計算
    void twoSum(vector<int> &nums, int n, int curStart, int target, vector<vector<int>> &ans)
    {
        int low = curStart, high = n - 1;
        while(low < high)
        {
            if((nums[low] + nums[high]) == target)
            {
                vector<int> tmpVec;
                tmpVec.push_back(0 - target);
                tmpVec.push_back(nums[low]);
                tmpVec.push_back(nums[high]);
                ans.push_back(tmpVec);
                
                int tmps = nums[low];
                while(low < high && nums[low] == tmps)
                    ++low;
                tmps = nums[high];
                while(low < high && nums[high] == tmps)
                    --high;
            } 
            else if((nums[low] + nums[high]) < target)
            {
                int tmps = nums[low];
                while(low < high && nums[low] == tmps)
                    ++low;
            }
            else
            {
                int tmps = nums[high];
                while(low < high && nums[high] == tmps)
                    --high;
            }
        }
    }
    
    vector<vector<int>> threeSum(vector<int>& nums) {
        int len = nums.size();
        vector<vector<int>> ans;
        if(len < 3)
            return ans;
        sort(nums.begin(), nums.end());
        int i = 0;
        while(i < len)
        {
            int tmptarget = 0 - nums[i];
            twoSum(nums, len, i + 1, tmptarget, ans);
            int tmps = nums[i];
            while(i < len && nums[i] == tmps)
                ++i;
        }
        return ans;
    }
};


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章