[LeetCode]21. 3Sum三者之和

Given an array S of n integers, are there elements abc in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.

Note:

  • Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c)
  • 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)

解法1:首先想到暴力破解,O(n^3)的时间复杂度,必然超时Time Limit Exceeded

class Solution {
public:
    vector< vector<int> > threeSum(vector<int>& nums) {
        int n = nums.size();
        vector< vector<int> > res;
        if (n < 3)
            return res;

        for (int i = 0; i < n; i++)
        {
            for (int j = i + 1; j < n; j++)
            {
                for (int k = j + 1; k < n; k++)
                {
                    if (nums[i] + nums[j] + nums[k] == 0)
                    {
                        vector<int> vi = adjust(nums[i], nums[j], nums[k]);
                        vector< vector<int> >::iterator iter = find(res.begin(), res.end(), vi);
                        if (iter == res.end())
                            res.push_back(vi);
                    }
                }
            }
        }
        return res;
    }
private:
    vector<int> adjust(int& a, int& b, int&c)
    {
        if (a > b)
            swap(a, b);
        if (a > c)
        {
            swap(a, c);
            swap(b, c);
        }
        else
        {
            if (b > c)
                swap(b, c);
        }
        vector<int> vi;
        vi.push_back(a);
        vi.push_back(b);
        vi.push_back(c);
        return vi;
    }
};

解法2:假设3sum问题的目标是target。每次从数组中选出一个数k,从剩下的数中求目标等于target-k的2sum问题。这里需要注意的是有个小的trick:当我们从数组中选出第i数时,我们只需要求数值中从第i+1个到最后一个范围内字数组的2sum问题。假设数组为A[],总共有n个元素A1,A2....An。很显然,当选出A1时,我们在子数组[A2~An]中求目标位target-A1的2sum问题,我们要证明的是当选出A2时,我们只需要在子数组[A3~An]中计算目标位target-A2的2sum问题,而不是在子数组[A1,A3~An]中,证明如下:

假设在子数组[A1,A3~An]目标位target-A2的2sum问题中,存在A1 + m = target-A2(m为A3~An中的某个数),即A2 + m = target-A1,这刚好是“对于子数组[A2~An],目标为target-A1的2sum问题”的一个解。即我们相当于对满足3sum的三个数A1+A2+m = target重复计算了。因此为了避免重复计算,在子数组[A1,A3~An]中,可以把A1去掉,再来计算目标是target-A2的2sum问题。

class Solution {
public:
    vector< vector<int> > threeSum(vector<int>& nums) {
        int n = nums.size();
        vector< vector<int> > res;
        if (n < 3)
            return res;
        sort(nums.begin(), nums.end());
        for(int i = 0; i < n; i++)
        {
            if(i == 0 ||  (i > 0 && nums[i] != nums[i - 1]))
            {
                int left = i + 1, right = n - 1;
                int sum = 0 - nums[i];
                while(left < right)
                {
                    if(nums[left] + nums[right] == sum)
                    {
                        vector<int> vi;
                        vi.push_back(nums[i]);
                        vi.push_back(nums[left]);
                        vi.push_back(nums[right]);
                        res.push_back(vi);
                        while(left < right && nums[left] == nums[left + 1])
                            left++;
                        while(left < right && nums[right] == nums[right - 1])
                            right--;
                        left++;
                        right--;
                    }
                    else if(nums[left] + nums[right] < sum)
                        left++;
                    else
                        right--;
                }
            }
        }
        return res;
    }
};

参考:http://www.cnblogs.com/tenosdoit/p/3649607.html

时间: 2024-10-17 01:53:17

[LeetCode]21. 3Sum三者之和的相关文章

LeetCode 016 3Sum Closest

[题目] Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution. For example, given array S = {

[LeetCode] 4Sum 四数之和

Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target. Note: Elements in a quadruplet (a,b,c,d) must be in non-descending order.

[Leetcode][016] 3Sum Closest (Java)

题目: https://leetcode.com/problems/3sum-closest/ [标签]Array; Two Pointers [个人分析] 这道题和它的姊妹题 3Sum 非常类似, 就不再多说了,具体一些的分析可以参考 [Leetcode][015] 3Sum 1 public class Solution { 2 public int threeSumClosest(int[] nums, int target) { 3 int result = target; 4 int

leetCode 15. 3Sum (3个数) 解题思路和方法

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: Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c) The

LeetCode 015 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: Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c) The

[LeetCode] 015. 3Sum (Medium) (C++/Java/Python)

索引:[LeetCode] Leetcode 题解索引 (C++/Java/Python/Sql) Github: https://github.com/illuz/leetcode 015.3Sum (Medium) 链接: 题目:https://oj.leetcode.com/problems/3sum/ 代码(github):https://github.com/illuz/leetcode 题意: 在给定数列中找出三个数,使和为 0. 分析: 先排序,再左右夹逼,复杂度 O(n*n).

LeetCode 21 23:Merge Two Sorted Lists &amp; Merge K Sorted Lists

LeetCode 21: Merge Two Sorted Lists Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists. 题目分析:对两个有序列表进行合并,这个是数据结构基本题目比较简单,代码如下(这个代码有点长,可以简化): ListNode *mergeTwoL

[C++]LeetCode: 70 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: Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c) The s

[LeetCode]21 Merge Two Sorted Lists 合并两个有序链表

---恢复内容开始--- [LeetCode]21 Merge Two Sorted Lists 合并两个有序链表 Description Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists. Example Example: Input: 1->2->4, 1-&g