Java实现三数之和等于0 -----(笔记)
import java.util.*;
public class Test {
public static void main(String[] args) {
threeSum(new int[]{-1,0,1,2,-1,-4});
}
public static List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> list = new ArrayList<>();
Arrays.sort(nums);
for(int i=0;i<nums.length;i++){
if(nums[i]>0){
break;
}
if(i>0 && nums[i-1] == nums[i]) continue;
int index = nums[i];
int j = i+1;
int k = nums.length-1;
while(j<k){
if(index + nums[j] + nums[k] == 0){
list.add(Arrays.asList(index,nums[j],nums[k]));
while(j<k && nums[j+1] == nums[j]){
j++;
}
while(j<k && nums[k-1] == nums[k]){
k--;
}
j++;
k--;
}else if(index + nums[j] + nums[k] > 0){
k--;
}else{
j++;
}
}
}
list.forEach(System.out::println);
return list;
}
}