|
6 | 6 |
|
7 | 7 | /**
|
8 | 8 | * 15. 3Sum
|
| 9 | + * |
9 | 10 | * Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0?
|
10 | 11 | * Find all unique triplets in the array which gives the sum of zero.
|
11 |
| -
|
12 |
| - Note: The solution set must not contain duplicate triplets. |
| 12 | + * |
| 13 | + * Note: The solution set must not contain duplicate triplets. |
13 | 14 |
|
14 | 15 | For example, given array S = [-1, 0, 1, 2, -1, -4],
|
15 | 16 |
|
|
22 | 23 |
|
23 | 24 | public class _15 {
|
24 | 25 |
|
25 |
| - public List<List<Integer>> threeSum(int[] nums) { |
26 |
| - List<List<Integer>> result = new ArrayList<>(); |
27 |
| - if (nums == null || nums.length == 0) { |
28 |
| - return result; |
29 |
| - } |
30 |
| - |
31 |
| - Arrays.sort(nums); |
32 |
| - for (int i = 0; i < nums.length; i++) { |
33 |
| - if (i >= 1 && nums[i] == nums[i - 1]) { |
34 |
| - continue; |
35 |
| - } |
36 |
| - int left = i + 1; |
37 |
| - int right = nums.length - 1; |
38 |
| - while (left < right) { |
39 |
| - int sum = nums[i] + nums[left] + nums[right]; |
40 |
| - if (sum == 0) { |
41 |
| - result.add(Arrays.asList(nums[i], nums[left], nums[right])); |
42 |
| - /**be sure to skip duplicates*/ |
43 |
| - while (left + 1 < right && nums[left] == nums[left + 1]) { |
| 26 | + public static class Solution1 { |
| 27 | + public List<List<Integer>> threeSum(int[] nums) { |
| 28 | + Arrays.sort(nums); |
| 29 | + List<List<Integer>> result = new ArrayList<>(); |
| 30 | + for (int i = 0; i < nums.length - 2; i++) { |
| 31 | + if (i >= 1 && nums[i] == nums[i - 1]) { |
| 32 | + continue; |
| 33 | + } |
| 34 | + int left = i + 1; |
| 35 | + int right = nums.length - 1; |
| 36 | + while (left < right) { |
| 37 | + int sum = nums[i] + nums[left] + nums[right]; |
| 38 | + if (sum == 0) { |
| 39 | + result.add(Arrays.asList(nums[i], nums[left], nums[right])); |
| 40 | + |
| 41 | + while (left + 1 < right && nums[left] == nums[left + 1]) { |
| 42 | + left++; |
| 43 | + } |
| 44 | + |
| 45 | + while (right - 1 > left && nums[right] == nums[right - 1]) { |
| 46 | + right--; |
| 47 | + } |
44 | 48 | left++;
|
45 |
| - } |
46 |
| - while (right - 1 > left && nums[right] == nums[right - 1]) { |
47 | 49 | right--;
|
| 50 | + } else if (sum > 0) { |
| 51 | + right--; |
| 52 | + } else { |
| 53 | + left++; |
48 | 54 | }
|
49 |
| - left++; |
50 |
| - right--; |
51 |
| - } else if (sum > 0) { |
52 |
| - right--; |
53 |
| - } else { |
54 |
| - left++; |
55 | 55 | }
|
56 | 56 | }
|
| 57 | + return result; |
57 | 58 | }
|
58 |
| - return result; |
59 | 59 | }
|
60 | 60 | }
|
0 commit comments