)
class Solution { public ListListInteger threeSum(int[] nums) { int n nums.length; // 先把数组升序排序是双指针的前提方便去重和移动指针 Arrays.sort(nums); ListListInteger ans new ArrayListListInteger(); //枚举第一个数 for (int first 0; first n; first) { // a去重如果当前a和上一轮a相同直接跳过避免产出一样的三元组 if (first 0 nums[first] nums[first - 1]) { continue; } int third n - 1; // 目标b c -a也就是 abc0 int target -nums[first]; // 枚举第二个数 for (int second first 1; second n; second) { // b去重 if (second first 1 nums[second] nums[second - 1]) { continue; } // 核心双指针bc target说明c太大了c左移变小 // 条件 second third必须保证b在c左边不能重合 while (second third nums[second] nums[third] target) { --third; } if (second third) { break; } if (nums[second] nums[third] target) { ListInteger list new ArrayListInteger(); list.add(nums[first]); list.add(nums[second]); list.add(nums[third]); ans.add(list); } } } return ans; } }