lintcode 三数之和

作者: yzawyx0220 | 来源:发表于2017-01-04 09:56 被阅读145次

    给出一个有n个整数的数组S,在S中找到三个整数a, b, c,找到所有使得a + b + c = 0的三元组。
    注意事项
    在三元组(a, b, c),要求a <= b <= c。
    结果不能包含重复的三元组。
    样例
    如S = {-1 0 1 2 -1 -4}, 你需要返回的三元组集合的是:
    (-1, 0, 1)
    (-1, -1, 2)
    题目链接:http://www.lintcode.com/zh-cn/problem/3sum/#

    先对数组进行排序,然后设置一个指针,从第三个数开始依次往后遍历,在这个指针指向的数之前再找到两个数,使三个数的和等于target即可。

    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
            sort(nums.begin(),nums.end());
            vector<vector<int> > res;
            for (int i = 2;i < nums.size();i++) {
                if (i+1 < nums.size() && nums[i] == nums[i+1]) continue;
                for (int j = i-1,k = 0,sum = nums[j] + nums[k],target = 0 - nums[i];k  < j;sum = nums[j] + nums[k]) {
                    if (sum < target || k > 0 && nums[k-1] == nums[k]) k++;
                    else if (sum > target || j+1 < i && nums[j] == nums[j+1]) j--;
                    else res.push_back({nums[k++],nums[j--],nums[i]});
                }
            }
            return res;
        }
    };
    

    相关文章

      网友评论

        本文标题:lintcode 三数之和

        本文链接:https://www.haomeiwen.com/subject/jfkpvttx.html