您的位置:首页 > 其它

LeetCode-15.3Sum

2016-04-05 16:04 309 查看
https://leetcode.com/problems/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 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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  算法 leetcode