|
| 1 | +package three_sum; |
| 2 | + |
| 3 | +import java.util.ArrayList; |
| 4 | +import java.util.Arrays; |
| 5 | +import java.util.Comparator; |
| 6 | +import java.util.List; |
| 7 | + |
| 8 | +class Solution { |
| 9 | + public List<List<Integer>> threeSum(int[] nums) { |
| 10 | + List<List<Integer>> collectSum = new ArrayList<>(); |
| 11 | + if (nums.length < 3 || nums.length > 3000) { |
| 12 | + return collectSum; |
| 13 | + } |
| 14 | + |
| 15 | + int totalNum = nums.length; |
| 16 | + Arrays.sort(nums); |
| 17 | + |
| 18 | + for (int i = 0; i < totalNum - 2; i++) { |
| 19 | + if (i > 0 && nums[i] == nums[i - 1]) { |
| 20 | + continue; |
| 21 | + } |
| 22 | + |
| 23 | + int iLeft = i + 1; |
| 24 | + int iRight = totalNum - 1; |
| 25 | + |
| 26 | + while (iLeft < iRight) { |
| 27 | + List<Integer> listSumNum = Arrays.asList(nums[iLeft], nums[i], nums[iRight]); |
| 28 | + int sumNum = nums[iLeft] + nums[i] + nums[iRight]; |
| 29 | + listSumNum.sort(Comparator.comparingInt(Integer::intValue)); |
| 30 | + |
| 31 | + if (sumNum == 0) { |
| 32 | + collectSum.add(listSumNum); |
| 33 | + |
| 34 | + while (iLeft < iRight && nums[iLeft] == nums[iLeft + 1]) { |
| 35 | + iLeft++; |
| 36 | + } |
| 37 | + |
| 38 | + while (iLeft < iRight && nums[iRight] == nums[iRight - 1]) { |
| 39 | + iRight--; |
| 40 | + } |
| 41 | + |
| 42 | + iLeft++; |
| 43 | + iRight--; |
| 44 | + } else if (sumNum < 0) { |
| 45 | + iLeft++; |
| 46 | + } else { |
| 47 | + iRight--; |
| 48 | + } |
| 49 | + } |
| 50 | + } |
| 51 | + |
| 52 | + collectSum.sort(Comparator.comparingInt(l -> l.get(0))); |
| 53 | + |
| 54 | + return collectSum; |
| 55 | + } |
| 56 | +} |
| 57 | + |
| 58 | +public class three_sum { |
| 59 | + public static void main(String[] args) { |
| 60 | + Solution solution = new Solution(); |
| 61 | + |
| 62 | + System.out.println(solution.threeSum(new int[] { -1, 0, 1, 2, -1, -4 })); // [[-1,-1,2],[-1,0,1]] |
| 63 | + System.out.println(solution.threeSum(new int[] { 0, 0, 0 })); // [[0,0,0]] |
| 64 | + System.out.println(solution.threeSum(new int[] { 3, -2, 1, 0 })); // [] |
| 65 | + System.out.println(solution.threeSum(new int[] { 1, -1, -1, 0 })); // [[-1,0,1]] |
| 66 | + System.out.println(solution.threeSum(new int[] { -1, 0, 1, 0 })); // [[-1,0,1]] |
| 67 | + System.out.println(solution.threeSum(new int[] { 2, -3, 0, -2, -5, -5, -4, 1, 2, -2, 2, 0, 2, -4, 5, 5, -10 })); |
| 68 | + // [[-10,5,5],[-5,0,5],[-4,2,2],[-3,-2,5],[-3,1,2],[-2,0,2]] |
| 69 | + |
| 70 | + } |
| 71 | +} |
0 commit comments