第一次尝试中等级别的题目,着实使我研究了好一会。
先排序一下,然后用c#定义三个两个指针,先定义一个初始指针用于外层for循环,然后前一个后一个,根据三者只和移动即可。
public static int[] GetBYn(int [] nums)
{
HashSet<triplet> hash = new HashSet<triplet>();
if (nums.Length<3)
return nums;
Array.Sort(nums);
for (int a = 0; a < nums.Length-1; a++)
{
int b = nums[a + 1];
int c = nums.Length - 1;
while (b<c)
{
if (nums[a]+nums[b]+nums[c]==0)
{
List<int> triplets = new List<int>() { nums[a], nums[b], nums[c] };
hash.Add(triplets);
b++;
c--;
}
else if (nums[a]+nums[b]+nums[c]>0)
{
c--;
}
else
{
b++;
}
}
}
return hash;
}
鸣谢同样为c#做LeetCode做出贡献的:https://www.cnblogs.com/etcow/articles/2547108.html