classSolution{ public List<List<Integer>> threeSum(int[] nums) { int n = nums.length; Arrays.sort(nums); List<List<Integer>> ans = new ArrayList<List<Integer>>();
//枚举 a for(int a = 0; a < n; a++){ //需要和上一次枚举的数不相同 if(a > 0 && nums[a] == nums[a - 1]){ continue; }
// c 对应的指针初始指向数组的最右端 int c = n - 1; int target = -nums[a]; //枚举 b for(int b = a + 1; b < n; ++b){ //需要和上一次枚举的数不相同,a 和 b 都不同,结果组合一定不会相同 if(b > a + 1 && nums[b] == nums[b - 1]){ continue; } // b 的指针在 c 指针左侧 while(b < c && nums[b] + nums[c] > target){ --c; }
//指针重合,随着 b 的增加就不会有满足 a+b+c=0 且 满足 b<c 的 c 了,退出循环 if(b == c){ break; }