【LeetCode】3Sum

来源:互联网 发布:小狐仙软件功能 编辑:程序博客网 时间:2024/06/06 02:13

算法小白,最近刷LeetCode。希望能够结合自己的思考和别人优秀的代码,对题目和解法进行更加清晰详细的解释,供大家参考^_^

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

题目的意思是说,在数组S中找到三个元素,使得这三个元素的和为0,同时还要求满足条件的所有三元组不能重复。
乍看一下,是个O(n^3)或者O(n^2*logn)的时间复杂度,实际上可以降低到O(n^2)的复杂度。
另一个要注意的就是重复三元组的问题,可以找到所有的三元组再使用unique函数剔除掉重复的部分,当然更好的方法是在添加三元组过程中保证唯一性。直接看代码:

class Solution {public:    vector<vector<int>> threeSum(vector<int>& nums) {        vector<vector<int> > res;        size_t len = nums.size();        sort(nums.begin(), nums.end()); //排序        for (int i = 0; i < len; ) {       //nums[i]作为三元组中的第一个数            int tar = 0 - nums[i];         //计算剩余两数的和             int beg = i + 1, end = len - 1; // 两个指针,分别指向候选的第二个数和第三个数            while (beg < end){                int sum = nums[beg] + nums[end];                if (sum > tar) --end;    //候选两数之和比tar大,说明end所指的数太大了,所以要往小的方向移动                else if (sum < tar) ++beg; //同上,往大的方向移动                else {                     //找到了满足要求的另两个数,加入到结果集中                    vector<int> tmp;                    tmp.push_back(nums[i]);                    tmp.push_back(nums[beg]);                    tmp.push_back(nums[end]);                    res.push_back(tmp);                        //跳过相同的第二个数和第三个数,继续查找                    while (beg < end && nums[beg] == tmp[1]) ++beg;                     while (beg < end && nums[end] == tmp[2]) --end;                }            }            //跳过相同的第一个数            while (nums[i] == nums[++i] && i < len);        }        return res;    }};

结果集中的三元组按照递增顺序排列,从而保证了唯一性,总体的时间复杂度为O(n^2)

0 0