3 Sum

Question

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: The solution set must not contain duplicate triplets.

1
2
3
4
5
6
7
For example, given array S = [-1, 0, 1, 2, -1, -4],

A solution set is:
[
  [-1, 0, 1],
  [-1, -1, 2]
]

Analysis

这道题的思路还算是比较清晰的,排序,然后两个指针一前一后搜索合适的解就可以了。主要是题目要求unique triplets,就需要合理的排除掉重复的解。

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
public:
    vector<vector<int>> threeSum(vector<int>& nums) {
        vector<vector<int>> res;
        sort(nums.begin(), nums.end());
        for (int i = 0; i < nums.size(); ++i) {
            for (int j=i+1, k=nums.size()-1; j< k; ) {
                if (nums[j] + nums[k] == - nums[i]) {
                    res.push_back({nums[i], nums[j], nums[k]});
                    while(j+1 < k && nums[j] == nums[j+1]) ++j;
                    while(k-1 > j && nums[k] == nums[k-1]) --k;
                    ++j; --k;
                } else if (nums[j] + nums[k] < - nums[i]) {
                    ++j;
                } else {
                    --k;
                }
            }
            while(i+1 < nums.size() && nums[i] == nums[i+1]) ++i;
        }
        return res;
    }
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Solution {
public:
    vector<vector<int>> threeSum(vector<int>& nums) {
        vector<vector<int> > res;
        sort(nums.begin(), nums.end());
        for (int i=0; i<(int)nums.size()-2; ++i) {
            if (i>0 && nums[i] == nums[i-1]) continue;
            // check backward, this is actually a good idea.
            // the benefit to check backward:
            // 1) make sure the element itself is checked;
            // 2) then check if current == previous value. Skip if so.
            int target = 0 - nums[i];
            int lo=i+1, hi=nums.size()-1;
            while(lo < hi) {
                if (nums[lo] + nums[hi] < target) ++lo;
                else if (nums[lo] + nums[hi] > target) --hi;
                else {
                    res.push_back({nums[i], nums[lo], nums[hi]});
                    //while(lo+1 <nums.size() && nums[lo] == nums[lo+1]) ++lo;
                    //++lo;
                    while(nums[lo] == nums[++lo]);
                }
            }
        }
        return res;
    }
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution(object):
    def threeSum(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        nums.sort()
        n, result = len(nums), []
        for i in range(n):
            if i > 0 and nums[i] == nums[i-1]: 
                continue
            target = -nums[i]
            l,h = i+1, n-1
            while l < h:
                if nums[l] + nums[h] == target:
                    result.append([nums[i], nums[l], nums[h]])
                    l += 1
                    while l < h and nums[l] == nums[l-1]:
                        l += 1
                elif nums[l] + nums[h] < target:
                    l += 1
                else:
                    h -= 1
        return result