题目描述
给你一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?请你找出所有满足条件且不重复的三元组。
注意:答案中不可以包含重复的三元组
给定数组 nums = [-1, 0, 1, 2, -1, -4],
满足要求的三元组集合为:
[
[-1, 0, 1],
[-1, -1, 2]
]
暴力法
输入的数组元素过多时,处理的时间会很长,超出时间限制,不推荐
private List<List<Integer>> directlySolution(int[] nums) {
if (nums == null || nums.length <= 2) {
return Collections.emptyList();
}
Arrays.sort(nums);
Set<List<Integer>> result = new LinkedHashSet<>();//这里用set集合存放结果
for (int i = 0; i < nums.length; i++) {
for (int j = i+1; j < nums.length; j++) {
for (int k = j+1; k < nums.length; k++) {
if (nums[i] + nums[j] + nums[k] == 0) {
result.add(Arrays.asList(nums[i], nums[j], nums[k]));
}
}
}
}
return new ArrayList<>(result);
}
双指针法
双指针法铺垫: 先将给定 nums 排序(从小到大),复杂度为 O(NlogN)O(NlogN)。
双指针法思路: 固定 3 个指针中最左(最小)数字的指针 i,双指针 head,tail分设在数组索引 (i, len(nums)) 两端,通过双指针交替向中间移动,记录对于每个固定指针 k 的所有满足 nums[i] + nums[head] + nums[tail] == 0 的 head,tail组合:
1.当 nums[i] > 0 时直接break跳出:因为k指针的值为最小值,若其的元素值大于0,则必定找不出满足条件的组合;
2.当 i > 0且nums[i] == nums[i- 1] 时即跳过此元素 nums[i],
因为已经将nums[i-1]的值加入到结果中,此步能避免重复。
3.head,tail分设在数组索引 (i, len(nums)) 两端,当head< tail时循环计算s = nums[i] + nums[head] + nums[tail],并按照以下规则执行双指针移动:
(1)当s < 0时,head+= 1;
(2)当s > 0时,tail -= 1;
(3)当s == 0时,记录组合[i,head,tail]至result,执行head+= 1和 tail-= 1并跳过所有重复的nums[head]和nums[tail],防止记录到重复组合。
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
if (nums == null || nums.length <= 2) {//输入的数组长度小于3则返回空
return Collections.emptyList();
}
Arrays.sort(nums);//排序,从小到大
List<List<Integer>> result = new LinkedList<>();//定义一个结果集,存放数组
for (int i = 0; i < nums.length - 2; i++) {
// c为非负数,就不能满足a+b+c=0了
if (nums[i] > 0) {
return result;
}
// 跳过计算过的数据,同时防止结果重复
if (i != 0 && nums[i] == nums[i-1]) {
continue;
}
int head = i + 1;
int tail = nums.length - 1;
while (head < tail) {
int sum = (nums[i]+nums[head] + nums[tail]);
if (sum == 0) {
result.add(Arrays.asList(nums[i], nums[head], nums[tail]));
// 跳过计算过的数据,同时防止结果重复
while (head < tail && nums[head] == nums[head+1]) {
head++;
}
while (head < tail && nums[tail] == nums[tail-1]) {
tail--;
}
}
if (sum >0) {
tail--;
} else {
head++;
}
}
}
return result;
}
}