三数之和
给你一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,
使得 a + b + c = 0 ?请你找出所有和为 0 且不重复的三元组。
思路:
1.对数组进行排序
2.确定一个数num[i],然后确定左边界和右边界
3.计算这个三个数之和,与0进行判断,更新左索引或者右索引
4.注意去除重复结果。1)跳过相同的num[i]。2)跳过索引值相同的左右索引。
public static List<List<Integer>> threeSum2(int[] nums){
int len = nums.length;
List<List<Integer>> list = new ArrayList<>();
if ( len < 3) return list;
Arrays.sort(nums);
for (int i = 0; i < len;i++){
int flag = nums[i];
if (flag > 0) break; // 如果当前数字大于0,则三数之和一定大于0,所以结束循环
if (i > 0 && flag == nums[i-1]) continue; //去重,当前i不执行
int l = i+1;
int r = len-1;
while (l<r){
int res = flag + nums[l]+ nums[r];
if ( res > 0){
r--;
}else if (res < 0){
l++;
}else {
list.add( Arrays.asList(flag, nums[l], nums[r]));
while (l<r && nums[l] == nums[l+1]) l++; // 去重
while (l<r && nums[r] == nums[r-1]) r--; // 去重
l++;
r--;
}
}
}
return list;
}