3Sum

1、結果爲vector < vector> res這樣的數組時,要記得先把res進行clear;
題目:
Given an array S of n integers, are there elements a, b, c 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)

思路:
1、從兩個參數的和變成三個參數的和,基本方法應該和兩個參數的一樣,只是多加了一個循環for(int i=0;i

class Solution {
public:
    vector<vector<int> > threeSum(vector<int> &num) {
        int len=num.size()-1;
        int sum=0;
        sort(num.begin(),num.end());
        vector<vector<int>> res;
        res.clear();
        for(int i=0;i<len;i++)
        {
            if(i>0 && num[i]==num[i-1]) continue;
            int j=i+1;
            int k=len;

            while(j<k)
            {
                if(j>i+1 && num[j]==num[j-1])
                {
                    j++;
                    continue;
                }
                if(k<len && num[k]==num[k+1])
                {
                    k--;
                    continue;
                }
                sum=num[i]+num[j]+num[k];
                if(sum>0) k--;
                else if(sum<0) j++;
                else{
                    vector<int>tmp;
                    tmp.push_back(num[i]);
                    tmp.push_back(num[j]);
                    tmp.push_back(num[k]);
                    res.push_back(tmp);
                    j++;
                }
            }

        }
        return res;
    }
};
發佈了19 篇原創文章 · 獲贊 7 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章