15. 3Sum (Medium)

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: 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]
]

Solution: Array + Two Pointers

这道题让我们求三数之和,比之前那道Two Sum 两数之和要复杂一些,我们还是要首先对原数组进行排序,然后开始遍历排序后的数组,这里注意不是遍历到最后一个停止,而是到倒数第三个就可以了,然后我们还要加上重复就跳过的处理,对于遍历到的数,我们用0减去这个数得到一个sum,我们只需要再之后找到两个数之和等于sum即可,这样一来问题又转化为了求two sum,这时候我们一次扫描,找到了等于sum的两数后,加上当前遍历到的数字,按顺序存入结果中即可,然后还要注意跳过重复数字。代码如下:

vector<vector<int>> threeSum(vector<int>& nums) {
    vector<vector<int>> res;
    sort(nums.begin(), nums.end());
    int n = nums.size();
    for (int i = 0; i < n-1; ++i) {
        if (nums[i] > 0) break;
        if (i >= 1 && nums[i] == nums[i-1]) continue;
        int target = -nums[i], l = i+1, r = n-1;
        while (l < r) {
            if (nums[l] + nums[r] == target) {
                res.push_back({nums[i], nums[l], nums[r]});
                while (l < r && nums[l] == nums[l+1]) ++l;
                while (l < r && nums[r] == nums[r-1]) --r;
                ++l; --r;
            } else if (nums[l] + nums[r] < target) ++l;
            else --r;
        }
    }
    return res;
}

results matching ""

    No results matching ""