题目
15. 三数之和
/*
- 给你一个整数数组 nums ,判断是否存在三元组 [nums[i], nums[j], nums[k]] 满足 i != j、i != k 且 j != k ,同时还满足 nums[i] + nums[j] + nums[k] == 0 。请你返回所有和为 0 且不重复的三元组。
- 注意:答案中不可以包含重复的三元组。
- 示例 1:
- 输入:nums = [-1,0,1,2,-1,-4]
- 输出:[[-1,-1,2],[-1,0,1]]
- 解释:
- nums[0] + nums[1] + nums[2] = (-1) + 0 + 1 = 0 。
- nums[1] + nums[2] + nums[4] = 0 + 1 + (-1) = 0 。
- nums[0] + nums[3] + nums[4] = (-1) + 2 + (-1) = 0 。
- 不同的三元组是 [-1,0,1] 和 [-1,-1,2] 。
- 注意,输出的顺序和三元组的顺序并不重要。
- 示例 2:
- 输入:nums = [0,1,1]
- 输出:[]
- 解释:唯一可能的三元组和不为 0 。
- 示例 3:
- 输入:nums = [0,0,0]
- 输出:[[0,0,0]]
- 解释:唯一可能的三元组和为 0 。
*/
具体实现
双指针
思路及算法:
思路:
确定首尾指针,不断去遍历首和中间元素值,并且筛选掉不符合条件的元素以及重复元素集合
int[] nums15 = new int[] { -1, 0, 1, 2, -1, -4 };
int[] nums15_1 = new int[] { 0, 1, 1 };
int[] nums15_2 = new int[] { 0, 0, 0 };
public IList<IList<int>> ThreeSum(int[] nums)
{
// 先对数组进行排序
Array.Sort(nums);
List<IList<int>> resultList = new List<IList<int>>();
// 外层循环,筛选首指针
for (int first = 0; first < nums.Length; first++)
{
// 如果 first > 0 并且 当前值和上一次first值相同,则视为重复数据,直接返回
if (first > 0 && nums[first] == nums[first - 1]) continue;
// 确定尾部指针
int third = nums.Length - 1;
// 确定目标值:first + second + third = 0
int target = -nums[first];
// 枚举首尾中间的元素值
for (int second = first + 1; second < nums.Length; second++)
{
// 当前值和上一次second值相同,则视为重复数据,直接返回
if (second > first + 1 && nums[second] == nums[second - 1]) continue;
// 保证 second 在 third 左侧,不然可能出现重复数据
while (second < third && nums[second] + nums[third] > target) --third;
// 如果中间元素和尾部指针重合(不足3个元素),就不会有满足 a+b+c=0 并且 b<c 的 c 了,可以退出循环
if (second == third) break;
if (nums[second] + nums[third] == target)
{
resultList.Add(new List<int>() { nums[first], nums[second], nums[third] });
}
}
}
return resultList;
}