#57 3Sum

題目描述:

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

 Notice

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.

Example

For example, given array S = {-1 0 1 2 -1 -4}, A solution set is:

(-1, 0, 1)
(-1, -1, 2)
題目思路:

這題有3個未知數,如果我們能定下一個未知數,剩下的兩個就可以用two pointers的方法來解決了。那這樣想就好辦了,我們可以把一個未知數從i = 2...A.size() - 1遍歷,然後剩下的兩個用two pointers來找到答案。

Mycode(AC = 13ms):

class Solution {
public:    
    /**
     * @param numbers : Give an array numbers of n integer
     * @return : Find all unique triplets in the array which gives the sum of zero.
     */
    vector<vector<int> > threeSum(vector<int> &nums) {
        // write your code here
        vector<vector<int>> ans;
        if (nums.size() <= 2) return ans;
        
        sort(nums.begin(), nums.end());
        
        set<vector<int>> visited;
        
        // traverse the 3rd number in array, 
        // use two pointers method to find 1st and
        // 2nd numbers
        for (int i = 2; i < nums.size(); i++) {
            int l = 0, r = i - 1;
            while (l < r) {
                if (nums[l] + nums[r] == -nums[i]) {
                    if (visited.find({nums[l], nums[r], nums[i]}) == visited.end()) {
                        visited.insert({nums[l], nums[r], nums[i]});
                        ans.push_back({nums[l], nums[r], nums[i]});
                    }
                    l++;
                    r--;
                }
                else if (nums[l] + nums[r] < -nums[i]) {
                    l++;
                }
                else {
                    r--;
                }
            }
        }
        
        return ans;
    }
};


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