1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
| class Solution { public List<List<Integer>> threeSum(int[] nums) {
int n = nums.length;
Arrays.sort(nums);
List<List<Integer>> res = new ArrayList<>();
int a, b, c;
for (int i = 0; i < n - 2; i++) { if ((a = nums[i]) > 0) break;
if (i != 0 && nums[i] == nums[i - 1]) continue;
for (int j = i + 1, k = n - 1; j < k;) { b = nums[j]; c = nums[k];
int sum = a + b + c;
if (sum == 0) { res.add(Arrays.asList(a, b, c));
while (j < k && nums[j] == nums[++j]); while (j < k && nums[k] == nums[--k]); } else if (sum < 0) { ++j; } else { --k; } } }
return res; } }
|