15. 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: 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 两数之和等于一个输入的数复杂一些.

解法1

可以先对数组排序,那为什么排序呢,是为了下面定义左右指针时候方便比较向中间靠拢.再遍历排序后的数组,如果定义第k个元素nums[k],求三个数的和为0,可以转换成求剩余的数中的某两个数的和为0-nums[k].这时候再定义左右指针,从两边网中间查找.由于数组是排序的,所以在遍历数组的时候不必全部遍历,因为数组是前一半为大于0,后一半为小于0.所以当k>0时候,就没有三个数的和等于0了,因为此时三个数都是大于0.

class Solution {
public:
    vector<vector<int>> threeSum(vector<int>& nums) {
        vector<vector<int>> res;
        sort(nums.begin(),nums.end());
        for (int k = 0;k < nums.size();k++)
        {
            //因为排序了, 到k>0时候应该结束
            if (nums[k] > 0) break;
            //排除相同数字
            if (k > 0 && nums[k]==nums[k-1]) continue;
            //转换成求两个数之和等于target
            int target = 0 - nums[k];
            int i = k + 1,j = 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;
    }
};

解法2

相对解法1, 这里只是用set来控制结果的重复问题

class Solution {
public:
    vector<vector<int>> threeSum(vector<int>& nums) {
        set<vector<int>> res;
        sort(nums.begin(), nums.end());
        for (int k = 0; k < nums.size(); ++k) {
            if (nums[k] > 0) break;
            int target = 0 - nums[k];
            int i = k + 1, j = 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());
    }
};
 
comments powered by Disqus