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: The solution set must not contain duplicate triplets.git
Given array S = [-1, 0, 1, 2, -1, -4], A solution set is: [ [-1, 0, 1], [-1, -1, 2] ]
难度:中
分析:要求给定的数组,找出知足条件的3个元素组合,使得3个元素之和等于零。注意,元素不能重复(值能够相同)。
思路:首先,咱们须要对数组进行排序,好比数组排序后变为[-4, -1, -1, 0, 1, 2],咱们判断第一个元素-4,判断它以后是否有2个元素的和等于4,若是有的话知足条件。由于数组已经排序,只要向当前元素以后查找便可,不用往前查找;
接下来,咱们开始遍历排序后的数组,假设当前元素是x,判断本次遍历有解的条件能够转化为找到当前元素以后2个元素和,应该等于0-x,使用夹逼查找方法,检查是否有解,若是有,增长到返回队列,没有的话,进入下一次的遍历,直至找到全部知足条件组合。github
public IList<IList<int>> ThreeSum(int[] nums) { //排序 Array.Sort(nums); var res = new List<IList<int>>(); //当前元素向后匹配2个元素,因此最后2个元素不用被遍历 for (int i = 0; i < nums.Length - 2; i++) { if (i == 0 || (i > 0 && nums[i] != nums[i - 1])) { int lo = i + 1, hi = nums.Length - 1, sum = 0 - nums[i]; while (lo < hi) { //找到知足条件元素,添加到返回结果队列 if (nums[lo] + nums[hi] == sum) { res.Add(new List<int> { nums[i], nums[lo], nums[hi] }); //防止重复元素 while (lo < hi && nums[lo] == nums[lo + 1]) lo++; while (lo < hi && nums[hi] == nums[hi - 1]) hi--; //夹逼查找 lo++; hi--; } else if (nums[lo] + nums[hi] < sum) lo++; else hi--; } } } return res; }