3sum
2018-02-12 11:08
253 查看
given an array s of integers n , 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.
code example :
/// <summary>
/// given an array s of n integers ,are there element 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:Element in triplets (a,b,c) must be in non-descending order
/// the solusion set must not contain duplicate triplets .
/// </summary>
/// <param name="nums"></param>
/// <returns></returns>
static List<List<int>> threeSum(int[] nums)
{
List<List<int>> result = new List<List<int>>();
if (nums.Length < 3) return result;
Array.Sort(nums);
int target = 0;
for(int i = 0; i < nums.Length - 2; ++i)
{
if (i > 0 && nums[i] == nums[i - 1]) continue;
int j = i + 1;
int k = nums.Length - 1;
while (j < k)
{
if (nums[i] + nums[j] + nums[k] < target)
{
++j;
while (nums[j] == nums[j - 1] && j < k) ++j;
}else if (nums[i] + nums[j] + nums[k] > target)
{
--k;
while (nums[k] == nums[k + 1] && j < k) --k;
}
else
{
result.Add(new List<int>() { nums[i], nums[j], nums[k] });
++j;
--k;
while (nums[j] == nums[j - 1] && j < k) ++j;
while (nums[k] == nums[k + 1] && j < k) --k;
}
}
}
return result;
}
code example :
/// <summary>
/// given an array s of n integers ,are there element 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:Element in triplets (a,b,c) must be in non-descending order
/// the solusion set must not contain duplicate triplets .
/// </summary>
/// <param name="nums"></param>
/// <returns></returns>
static List<List<int>> threeSum(int[] nums)
{
List<List<int>> result = new List<List<int>>();
if (nums.Length < 3) return result;
Array.Sort(nums);
int target = 0;
for(int i = 0; i < nums.Length - 2; ++i)
{
if (i > 0 && nums[i] == nums[i - 1]) continue;
int j = i + 1;
int k = nums.Length - 1;
while (j < k)
{
if (nums[i] + nums[j] + nums[k] < target)
{
++j;
while (nums[j] == nums[j - 1] && j < k) ++j;
}else if (nums[i] + nums[j] + nums[k] > target)
{
--k;
while (nums[k] == nums[k + 1] && j < k) --k;
}
else
{
result.Add(new List<int>() { nums[i], nums[j], nums[k] });
++j;
--k;
while (nums[j] == nums[j - 1] && j < k) ++j;
while (nums[k] == nums[k + 1] && j < k) --k;
}
}
}
return result;
}
相关文章推荐
- LeetCode: 3Sum
- leetcode001:3sum solution
- LeetCode 16: 3Sum Closest
- leetcode: 3Sum Closest
- 3Sum Closest
- Leetcode:3Sum Closest
- [LeetCode]3sum
- LeetCode 3Sum Closest
- [leet code] 3Sum Closest
- 3Sum Closest
- leetcode-3Sum Closest
- 【LeetCode】3Sum
- [LeetCode] 3Sum
- 【leetcode】3SumClosest
- 3Sum
- 【Leetcode】3Sum
- LeetCode 15. 3Sum
- [leetcode] 3Sum
- LeetCode @ 3Sum D3F5
- 程序员面试题目总结--数组(27)【Two Sum 、3Sum、3Sum Closest 、4Sum】