In the Leetcode 3Sum problem solution in C# programming Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0.
Notice that the solution set must not contain duplicate triplets.
Leetcode 3Sum problem solution in C# programming
public class Solution {
public IList<IList<int>> ThreeSum(int[] nums)
{
Array.Sort(nums);
var res = new List<IList<int>>();
for (int i = 0; i < nums.Length && nums[i] <= 0; ++i)
{
if (i == 0 || nums[i - 1] != nums[i])
{
TwoSum(nums, i, res);
}
}
return res;
}
private void TwoSum(int[] nums, int i, List<IList<int>> res)
{
var a = i + 1;
var b = nums.Length - 1;
while (a < b)
{
var sum = nums[i] + nums[a] + nums[b];
if (sum < 0 || (a > i + 1 && nums[a] == nums[a - 1]))
++a;
else if (sum > 0 || (b < nums.Length - 1 && nums[b] == nums[b + 1]))
--b;
else
{
var item = new List<int>();
item.Add(nums[i]);
item.Add(nums[a++]);
item.Add(nums[b--]);
res.Add(item);
}
}
}
}
Also read,
- Leetcode 3Sum problem solution in C++
- Leetcode 3Sum problem solution in Java
- Leetcode 3Sum problem solution in Python
- Leetcode 3Sum problem solution in C