[LeetCode] 15. 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)

 

這道題讓我們求三數之和,比之前那道 Two Sum 要復雜一些,博主考慮過先 fix 一個數,然后另外兩個數使用 Two Sum 那種 HashMap 的解法,但是會有重復結果出現,就算使用 TreeSet 來去除重復也不行,會 TLE,看來此題並不是考 Two Sum 的解法。來分析一下這道題的特點,要找出三個數且和為0,那么除了三個數全是0的情況之外,肯定會有負數和正數,還是要先 fix 一個數,然后去找另外兩個數,只要找到兩個數且和為第一個 fix 數的相反數就行了,既然另外兩個數不能使用 Two Sum 的那種解法來找,如何能更有效的定位呢?我們肯定不希望遍歷所有兩個數的組合吧,所以如果數組是有序的,那么就可以用雙指針以線性時間復雜度來遍歷所有滿足題意的兩個數組合。

對原數組進行排序,然后開始遍歷排序后的數組,這里注意不是遍歷到最后一個停止,而是到倒數第三個就可以了。這里可以先做個剪枝優化,就是當遍歷到正數的時候就 break,為啥呢,因為數組現在是有序的了,如果第一個要 fix 的數就是正數了,則后面的數字就都是正數,就永遠不會出現和為0的情況了。然后還要加上重復就跳過的處理,處理方法是從第二個數開始,如果和前面的數字相等,就跳過,因為不想把相同的數字fix兩次。對於遍歷到的數,用0減去這個 fix 的數得到一個 target,然后只需要再之后找到兩個數之和等於 target 即可。用兩個指針分別指向 fix 數字之后開始的數組首尾兩個數,如果兩個數和正好為 target,則將這兩個數和 fix 的數一起存入結果中。然后就是跳過重復數字的步驟了,兩個指針都需要檢測重復數字。如果兩數之和小於 target,則將左邊那個指針i右移一位,使得指向的數字增大一些。同理,如果兩數之和大於 target,則將右邊那個指針j左移一位,使得指向的數字減小一些,代碼如下:

 

解法一:

class Solution {
public:
    vector<vector<int>> threeSum(vector<int>& nums) {
        vector<vector<int>> res;
        sort(nums.begin(), nums.end());
        if (nums.empty() || nums.back() < 0 || nums.front() > 0) return {};
        for (int k = 0; k < (int)nums.size() - 2; ++k) {
            if (nums[k] > 0) break;
            if (k > 0 && nums[k] == nums[k - 1]) continue;
            int target = 0 - nums[k], i = k + 1, j = (int)nums.size() - 1;
            while (i < j) {
                if (nums[i] + nums[j] == target) {
                    res.push_back({nums[k], nums[i], nums[j]});
                    while (i < j && nums[i] == nums[i + 1]) ++i;
                    while (i < j && nums[j] == nums[j - 1]) --j;
                    ++i; --j;
                } else if (nums[i] + nums[j] < target) ++i;
                else --j;
            }
        }
        return res;
    }
};

 

或者我們也可以利用 TreeSet 的不能包含重復項的特點來防止重復項的產生,那么就不需要檢測數字是否被 fix 過兩次,不過個人覺得還是前面那種解法更好一些,參見代碼如下:

 

解法二:

class Solution {
public:
    vector<vector<int>> threeSum(vector<int>& nums) {
        set<vector<int>> res;
        sort(nums.begin(), nums.end());
        if (nums.empty() || nums.back() < 0 || nums.front() > 0) return {};
        for (int k = 0; k < (int)nums.size() - 2; ++k) {
            if (nums[k] > 0) break;
            int target = 0 - nums[k], i = k + 1, j = (int)nums.size() - 1;
            while (i < j) {
                if (nums[i] + nums[j] == target) {
                    res.insert({nums[k], nums[i], nums[j]});
                    while (i < j && nums[i] == nums[i + 1]) ++i;
                    while (i < j && nums[j] == nums[j - 1]) --j;
                    ++i; --j;
                } else if (nums[i] + nums[j] < target) ++i;
                else --j;
            }
        }
        return vector<vector<int>>(res.begin(), res.end());
    }
};

 

Github 同步地址:

https://github.com/grandyang/leetcode/issues/15

 

類似題目:

Two Sum

3Sum Smaller

3Sum Closest

4Sum

 

參考資料:

https://leetcode.com/problems/3sum/

https://leetcode.com/problems/3sum/discuss/7380/Concise-O(N2)-Java-solution

https://leetcode.com/problems/3sum/discuss/7373/Share-my-simple-java-solution

http://www.lifeincode.net/programming/leetcode-two-sum-3-sum-3-sum-closest-and-4-sum-java/

 

LeetCode All in One 題目講解匯總(持續更新中...)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM