class Solution {
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> result = new ArrayList<>();
//判断参数
if(nums.length < 3){
return result;
}
//首先对数组排序
Arrays.sort(nums);
//确定一个数另外两个数字使用双指针的方式来检索
for(int i = 0;i < nums.length - 2;){
//另外两个数自行调用双指针函数来解决
search(nums,i,result);
//解决完毕之后需要排除重复元素带来的干扰
int temp = nums[i];
while(i < nums.length && temp == nums[i]){
i++;
}
}
return result;
}
public void search(int[] nums,int index,List<List<Integer>> result){
//创建双指针
int opt1 = index + 1;
int opt2 = nums.length - 1;
//遍历数组元素判断双指针
while(opt1 < opt2){
if(nums[opt1] + nums[opt2] < -nums[index]){
opt1++;
}else if(nums[opt1] + nums[opt2] > -nums[index]){
opt2--;
}else{
//添加结果集
List<Integer> item = new ArrayList<Integer>();
item.add(nums[index]);
item.add(nums[opt1]);
item.add(nums[opt2]);
result.add(item);
//排除重复元素带来的影响
int temp = nums[opt1];
while(temp == nums[opt1] && opt1 < opt2){
opt1++;
}
}
}
}
}
数组中寻找三个数之和等于0java实现
最新推荐文章于 2022-12-17 21:31:23 发布