3Sum

Given an array nums of n integers, are there elements a, b, c in nums 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.

Example:

Given array nums = [-1, 0, 1, 2, -1, -4],

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


给定一个包含n个整数的数组nums,判断该数组中是否存在整数a、b、c,使它们满足a+b+c=0?找出所有满足该条件的整数。
注意:找出的3个数不可完全相同。

分析:
为求三个数的和为0,可先固定一个数ai,再在数组中找其余两个数aj、ak,使它们满足aj+ak=-ai。
为加快查找速度,可先对数组排序,这样当遍历该数组时,当遍历到第i个元素时,若ai大于0,可提前终止遍历,因为后面的数只可能是大于或等于它,ai+aj+ak必大于0。若ai小于等于0,从ai+1到an-1中查找满足条件的数。代码如下:
    vector<vector<int>> threeSum(vector<int>& nums) {
        vector<vector<int>> rst;
        int cnt = nums.size();
        if (cnt < 3)
            return rst;
        int target = 0, left = 0, right = 0, tmp = 0;
        sort(nums.begin(), nums.end());
        if (nums[0] > 0 || nums[cnt - 1] < 0)
            return rst;
        for (int i = 0; i < cnt - 2; i++)
        {
            if (nums[i] > 0)
                break;
            if (i > 0 && nums[i] == nums[i - 1])
                continue;
            target = 0 - nums[i];
            left = i + 1;
            right = cnt - 1;
            while (left < right)
            {
                tmp = nums[left] + nums[right];
                if (tmp == target)
                {
                    rst.push_back({ nums[i],nums[left],nums[right] });
                    while (left < right)
                    {
                        if (nums[left] != nums[left + 1])
                            break;
                        left++;
                    }
                    while (left < right)
                    {
                        if (nums[right] != nums[right - 1])
                            break;
                        right--;
                    }
                    left++;
                    right--;
                }
                else if (tmp < target)
                    left++;
                else
                    right--;
            }
        }
        return rst;
    }

 

上一篇:Leetcode 3Sum


下一篇:LC15-3Sum