|
| 1 | +class Solution { |
| 2 | + public List<List<Integer>> threeSum(int[] nums) { |
| 3 | + /** |
| 4 | + 1. understanding |
| 5 | + - integer array nums, find the whole combination of 3 nums, and the sum of the 3 nums equal to 0. And don't allow reusing same indiced number(but can duplicate in value) |
| 6 | + 2. solve strategy |
| 7 | + - brute force |
| 8 | + - in every combination, validate sum of the nums equal to 0 |
| 9 | + - but it can take O(N^3) times where N is the length of input array, and given that the N can be 3000 at most(3 * 10^3), time can be 27 * 10^9, which takes too long... |
| 10 | + - sort and two pointers |
| 11 | + - sort nums in ascending order, so move the left pointer to right means the sum of window is getting bigger. |
| 12 | + - and mid pointer set to left + 1 index |
| 13 | + - if sum of pointers is less than 0, then move mid pointer to right, until the sum is bigger than 0, and while processing them, if the sum of pointers is 0, then add the combination to the return list. |
| 14 | + - [-4, -1, -1, 0, 1, 2]: |
| 15 | + |
| 16 | + 3. complexity |
| 17 | + - time: O(N^2) -> each left pointer, you can search at most N-1, and left pointer's range is [0, N-1), so the max length is N-1 for left index pointer. |
| 18 | + - space: O(1) -> no extra space is needed |
| 19 | + */ |
| 20 | + // 0. assign return variable Set |
| 21 | + Set<List<Integer>> answer = new HashSet<>(); |
| 22 | + |
| 23 | + // 1. sort the num array in ascending order |
| 24 | + Arrays.sort(nums); // O(NlogN) |
| 25 | + // Arrays.stream(nums).forEach(System.out::println); |
| 26 | + |
| 27 | + // 3. move the mid pointer from left to right to find the combination of which's sum is 0, and if the sum is over 0, and then move right pointer to the left. else if the sum is under 0, then move left pointer to right direction. |
| 28 | + for (int left = 0; left < nums.length - 1; left++) { |
| 29 | + int mid = left + 1; |
| 30 | + int right = nums.length - 1; |
| 31 | + while (mid < right) { |
| 32 | + // System.out.println(String.format("%d,%d,%d", nums[left], nums[mid], nums[right])); |
| 33 | + int sum = nums[left] + nums[mid] + nums[right]; |
| 34 | + if (sum > 0) { |
| 35 | + right--; |
| 36 | + } else if (sum == 0) { |
| 37 | + answer.add(List.of(nums[left], nums[mid], nums[right])); |
| 38 | + right--; |
| 39 | + } else { |
| 40 | + mid++; |
| 41 | + } |
| 42 | + } |
| 43 | + } |
| 44 | + |
| 45 | + return new ArrayList<>(answer); |
| 46 | + } |
| 47 | +} |
| 48 | + |
0 commit comments