diff --git a/src/main/java/s0015.three.sum/Solution.java b/src/main/java/s0015.three.sum/Solution.java new file mode 100644 index 000000000..c0c7de0d8 --- /dev/null +++ b/src/main/java/s0015.three.sum/Solution.java @@ -0,0 +1,44 @@ +package s0015.three.sum; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +public class Solution { + public List> threeSum(int[] nums) { + Arrays.sort(nums); + final int len = nums.length; + List> result = new ArrayList<>(); + int l = 0, r = 0; + for (int i = 0; i < len - 2; i++) { + l = i + 1; + r = len - 1; + while (r > l) { + int sum = nums[i] + nums[l] + nums[r]; + if (sum < 0) { + l++; + } else if (sum > 0) { + r--; + } else { + List list = new ArrayList<>(); + list.add(nums[i]); + list.add(nums[l]); + list.add(nums[r]); + result.add(list); + while (l < r && nums[l + 1] == nums[l]) { + l++; + } + while (r > l && nums[r - 1] == nums[r]) { + r--; + } + l++; + r--; + } + } + while (i < len - 1 && nums[i + 1] == nums[i]) { + i++; + } + } + return result; + } +} diff --git a/src/test/java/s0015.three.sum/SolutionTest.java b/src/test/java/s0015.three.sum/SolutionTest.java new file mode 100644 index 000000000..585add034 --- /dev/null +++ b/src/test/java/s0015.three.sum/SolutionTest.java @@ -0,0 +1,15 @@ +package s0015.three.sum; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.MatcherAssert.assertThat; + +import org.junit.Test; + +public class SolutionTest { + @Test + public void threeSum() { + assertThat( + new Solution().threeSum(new int[] {-1, 0, 1, 2, -1, -4}).toString(), + equalTo("[[-1, -1, 2], [-1, 0, 1]]")); + } +}