Leetcode——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)

这道题让我想起了Leetcode的第一道题,即2Sum。很多人跟我说这两道题很像,但是我做完之后感觉一点都不像。

在2Sum这道题里面,Leetcode对时间的要求很高,所以用的是hash table的思想来解决的,即把value为key,position作为value,如果有冲突的话可以在一个bucket里放多个value。这样的话复杂度就只有O(n)。

3Sum不一样,是确定一个值之后来确定另外两个值。确定另外两个值复杂度最低也是O(n),所以总体的复杂度是O(n^n)。

仔细观察题目,第一个要求是要将数组以增序输出,所以我们最好将整个数组排序,复杂度为O(n^n),最低为O(nlogn)(使用快排)。排序对后面的扫描是相当有用的。

第二个要求是不能重复。初看上去挺难的,其实很简单,只需要在扫描的过程中跳过重复的既可。

代码如下,思路比较简单:

class Solution
{
public:
    vector< vector<int> > threeSum(vector<int>& nums)
    {
        vector< vector<int> > result;
        result.clear();
        unsigned int i;
        unsigned int j;
        unsigned int k;
        int sum;
        if (nums.size() < 3)
        {
            return result;
        }

        bubble_sort(nums);  //首先进行从小到大排序
        i = 0;
        while (i < nums.size() - 2)
        {
            j = i + 1;
            k = nums.size() - 1;
            while (j < k)
            {
                sum = nums[i] + nums[j] + nums[k];
                if (0 == sum)   //和为0时,需要去除那些重复的数字
                {
                    vector<int> triplet;
                    triplet.push_back(nums[i]);
                    triplet.push_back(nums[j]);
                    triplet.push_back(nums[k]);
                    result.push_back(triplet);
                    //去除重复
                    while (j < k && nums[j] == triplet[1]) j++;     //去重又自增,这个循环总会执行至少一遍
                    while (j < k && nums[k] == triplet[2]) k--;
                }
                else if (sum > 0)   //和大于0,k必须向左移动降低组合的值
                {
                    k--;
                }
                else
                {
                    j++;
                }
            }

            int temp = nums[i];
            while (i < nums.size() - 2 && nums[i] == temp) i++;
        }
        return result;
    }

private:
    void bubble_sort(vector<int>& nums) //冒泡排序
    {
        bool is_swap;

        for (unsigned int i = nums.size() - 1; i > 0; i--)
        {
            is_swap = false;
            for (unsigned int j = 0; j < i; j++)
            {
                if (nums[j] > nums[j+1])
                {
                    swap(nums[j], nums[j+1]);
                    is_swap = true;
                }
            }
            if (false == is_swap)
            {
                break;
            }
        }
    }

    void swap(int& a, int& b)
    {
        int temp = a;
        a = b;
        b = temp;
    }
};

参考文章:

http://blog.csdn.net/zhouworld16/article/details/16917071

http://blog.csdn.net/nanjunxiao/article/details/12524405

时间: 2024-10-10 03:52:13

Leetcode——3Sum的相关文章

[leetcode]3Sum Closest @ Python

原题地址:http://oj.leetcode.com/problems/3sum-closest/ 题意:数组中每三个元素进行求和,找出所有和中大小最接近target的和,并返回这个和与target之间的差值. 解题思路:使用一个变量mindiff来监测和与target之间的差值,如果差值为0,直接返回sum值. 代码: class Solution: # @return an integer def threeSumClosest(self, num, target): num.sort()

leetcode 3Sum 3Sum Closest 4Sum

这几个题很典型也是国外一些知名公司经常会问到的题 3Sum: 排序,避免重复,时间复杂度O(n^2) class Solution { public: vector<vector<int> > threeSum(vector<int> &num) { int len=num.size(); sort(num.begin(),num.begin()+len); vector<vector<int> > ret; ret.clear(); i

leetcode:3sum closet

题目:给一个数组和给定的目标值,要求在数组里找出三个元素,这三个元素的和最接近目标值,当然等于是最好的. 用3sum的方法,把判定条件作些修改. int twoSum(vector<int> &num, int start, int target) { if(num.size() < 3 || start >= num.size()) return -target; int head = start; int tail = num.size() - 1; int resul

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

[LeetCode] 3Sum Closest

This problem is very similar to 3Sum. You only need to maintain a variable for the sum that is closet to target. Also, some corner cases need to be handled; for example, nums does not have more than 2 elements. The code is as follows, which is quite

[LeetCode] 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 = {-1 2

LeetCode——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 = {-1 2

LeetCode——3Sum &amp; 3Sum Closest

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)

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