|
23 | 23 |
|
24 | 24 | public class _18 { |
25 | 25 |
|
26 | | - public List<List<Integer>> fourSum(int[] nums, int target) { |
27 | | - List<List<Integer>> result = new ArrayList(); |
28 | | - if (nums == null || nums.length == 0) { |
29 | | - return result; |
30 | | - } |
31 | | - Arrays.sort(nums); |
32 | | - for (int i = 0; i < nums.length - 3; i++) { |
33 | | - if (i > 0 && nums[i - 1] == nums[i]) { |
34 | | - continue; |
| 26 | + public static class Solution1 { |
| 27 | + public List<List<Integer>> fourSum(int[] nums, int target) { |
| 28 | + List<List<Integer>> result = new ArrayList(); |
| 29 | + if (nums == null || nums.length == 0) { |
| 30 | + return result; |
35 | 31 | } |
36 | | - for (int j = i + 1; j < nums.length - 2; j++) { |
37 | | - if (j > i + 1 && nums[j - 1] == nums[j]) { |
| 32 | + Arrays.sort(nums); |
| 33 | + for (int i = 0; i < nums.length - 3; i++) { |
| 34 | + if (i > 0 && nums[i - 1] == nums[i]) { |
38 | 35 | continue; |
39 | 36 | } |
40 | | - int left = j + 1; |
41 | | - int right = nums.length - 1; |
42 | | - while (left < right) { |
43 | | - int sum = nums[i] + nums[j] + nums[left] + nums[right]; |
44 | | - if (sum == target) { |
45 | | - result.add(Arrays.asList(nums[i], nums[j], nums[left], nums[right])); |
46 | | - while (left + 1 < right && nums[left] == nums[left + 1]) { |
| 37 | + for (int j = i + 1; j < nums.length - 2; j++) { |
| 38 | + if (j > i + 1 && nums[j - 1] == nums[j]) { |
| 39 | + continue; |
| 40 | + } |
| 41 | + int left = j + 1; |
| 42 | + int right = nums.length - 1; |
| 43 | + while (left < right) { |
| 44 | + int sum = nums[i] + nums[j] + nums[left] + nums[right]; |
| 45 | + if (sum == target) { |
| 46 | + result.add(Arrays.asList(nums[i], nums[j], nums[left], nums[right])); |
| 47 | + while (left + 1 < right && nums[left] == nums[left + 1]) { |
| 48 | + left++; |
| 49 | + } |
| 50 | + while (right - 1 > left && nums[right] == nums[right - 1]) { |
| 51 | + right--; |
| 52 | + } |
47 | 53 | left++; |
48 | | - } |
49 | | - while (right - 1 > left && nums[right] == nums[right - 1]) { |
50 | 54 | right--; |
| 55 | + } else if (sum > target) { |
| 56 | + right--; |
| 57 | + } else { |
| 58 | + left++; |
51 | 59 | } |
52 | | - left++; |
53 | | - right--; |
54 | | - } else if (sum > target) { |
55 | | - right--; |
56 | | - } else { |
57 | | - left++; |
58 | 60 | } |
59 | 61 | } |
60 | 62 | } |
| 63 | + return result; |
61 | 64 | } |
62 | | - return result; |
63 | 65 | } |
64 | | - |
65 | 66 | } |
0 commit comments