题目
输入一个数组,如何找出数组中所有和为0的3个数字的三元组?需要注意的是,返回值中不得包含重复的三元组。
分析
如果输入的数组是排序的,就可以先固定一个数字i,然后在排序数组中查找和为-i的两个数字。如何去除重复的三元组,需要使用两个指针来找出和为给定值的两个数字。在找到一个和为0的三元组之后,就需要移动这两个指针,以便找出其他符合条件的三元组。在移动指针的时候需要跳过所有相同的值。代码如下:
//TODO 数组中和为0的3个数字
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> result = new LinkedList<List<Integer>>();
if (nums.length >= 3) {
Arrays.sort(nums);
int i = 0;
while (i < nums.length - 2) {
twoSum(nums, i, result);
int temp = nums[i];
while (i < nums.length && temp == nums[i]) {
++i;
}
}
}
return result;
}
private void twoSum(int[] nums, int i, List<List<Integer>> result) {
int j = i + 1;
int k = nums.length - 1;
while (j < k) {
if (nums[i] + nums[j] + nums[k] == 0) {
result.add(Arrays.asList(nums[i], nums[j], nums[k]));
int temp = nums[j];
while (nums[j] == temp && j < k) {
++j;
}
} else if (nums[i] + nums[j] + nums[k] < 0) {
++j;
}else {
--k;
}
}
}