Skip to content

Commit

Permalink
Added task 15.
Browse files Browse the repository at this point in the history
  • Loading branch information
javadev committed Jul 7, 2021
1 parent 4c1f088 commit 454c4e0
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 0 deletions.
44 changes: 44 additions & 0 deletions src/main/java/s0015.three.sum/Solution.java
Original file line number Diff line number Diff line change
@@ -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<List<Integer>> threeSum(int[] nums) {
Arrays.sort(nums);
final int len = nums.length;
List<List<Integer>> 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<Integer> 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;
}
}
15 changes: 15 additions & 0 deletions src/test/java/s0015.three.sum/SolutionTest.java
Original file line number Diff line number Diff line change
@@ -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]]"));
}
}

0 comments on commit 454c4e0

Please sign in to comment.