LeetCode-15.3Sum

来源:互联网 发布:重生之网络霸主txt 编辑:程序博客网 时间:2024/06/04 22:43

https://leetcode.com/problems/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)

public IList<IList<int>> ThreeSum(int[] nums)    {        IList<IList<int>> res = new List<IList<int>>();        int n = nums.Length;        if (n < 3)            return res;        Array.Sort(nums);        int target,l,r;        for (int i = 0; i < n-2; i++)        {            target = -nums[i];            l = i + 1;            r = n - 1;            while (l<r)            {                if (nums[l] + nums[r] > target)                    r--;                else if (nums[l] + nums[r] < target)                    l++;                else                {                    res.Add(new List<int>() { nums[i], nums[l] ,nums[r] });                    while (i < n - 2 && nums[i] == nums[i + 1])                        i++;                    while (l < n - 1 && nums[l] == nums[++l]);                    while (r > i + 1 && nums[r] == nums[--r]);                }            }        }        return res;    }


0 0
原创粉丝点击