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.
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;
}
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;
}
相关文章推荐
- 书评:《算法之美( Algorithms to Live By )》
- 动易2006序列号破解算法公布
- Ruby实现的矩阵连乘算法
- C#插入法排序算法实例分析
- 超大数据量存储常用数据库分表分库算法总结
- C#数据结构与算法揭秘二
- C#冒泡法排序算法实例分析
- 算法练习之从String.indexOf的模拟实现开始
- C#算法之关于大牛生小牛的问题
- C#实现的算24点游戏算法实例分析
- c语言实现的带通配符匹配算法
- 浅析STL中的常用算法
- 算法之排列算法与组合算法详解
- C++实现一维向量旋转算法
- Ruby实现的合并排序算法
- C#折半插入排序算法实现方法
- 基于C++实现的各种内部排序算法汇总
- C++线性时间的排序算法分析
- C++实现汉诺塔算法经典实例
- PHP实现克鲁斯卡尔算法实例解析