3Sum——解題報告,3sum解題

來源:互聯網
上載者:User

3Sum——解題報告,3sum解題


    【題目】

     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)


    【分析】

    我們做過這樣的題目,給定一個數組和一個target,找出數組中的a+b = target。那麼這道題目變成了a,b,c三個數。

    其實,我們遍曆每個a,然後target' = targer - a. 也就變成了找出b+c = target'。和上面的題目一樣吧~


    【代碼】

    上述解法的時間複雜度最快也只能達到O(n^2)。

    需要解釋的是,下面給出的代碼在LeetCode提交的時候,一直是LTE。線下測試時對的,尋找了答案之後發現,主體思路一樣,只不過我用到的是set去重,可能這部分比較耗時。。。


vector< vector<int> > threeSum(vector<int>& nums) {    //if(nums.empty())        //return;            sort(nums.begin(), nums.end());    set< vector<int> > res1;     set< vector<int> >::iterator iter;    vector< vector<int> > res2;vector<int> tmp;        if(nums.size() < 3)        return res2;            for(int i = 0; i < nums.size() - 2; i++)    {        int current = nums[i];         int diff = 0 - current; // the target                int head = i + 1, tail = nums.size() - 1;        while(head < tail)        {            if(head == i)  // skip the current                {head++; continue;}            if(tail == i)                {tail--; continue;}                        if(nums[head] + nums[tail] == diff)            {//cout<<i<<' '<<head<<' '<<tail<<endl;                tmp.push_back(current); tmp.push_back(nums[head]); tmp.push_back(nums[tail]);                sort(tmp.begin(), tmp.end());  // sort//cout<<tmp[0]<<' '<<tmp[1]<<' '<<tmp[2]<<endl;//cout<<current<<' '<<nums[head]<<' '<<nums[tail]<<endl;                res1.insert(tmp);  // insert into the settmp.clear();                head++;                tail--;                continue;            }            else if(nums[head] + nums[tail] < diff)            {                head++;                continue;            }            else            {                tail--;                continue;            }        }    }        for(iter = res1.begin(); iter != res1.end(); ++iter)        res2.push_back(*iter);        return res2;}

下面給出一個ac的參考答案:

http://bbs.csdn.net/topics/390931100


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.