Skip to content

Commit

Permalink
TwoPointerTest - threeSum()
Browse files Browse the repository at this point in the history
  • Loading branch information
bky373 committed Jun 6, 2024
1 parent db96d2f commit c2363e7
Showing 1 changed file with 32 additions and 0 deletions.
32 changes: 32 additions & 0 deletions src/test/java/TwoPointerTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -30,4 +30,36 @@ void twoSum() {
}
assertThat(res).containsExactlyInAnyOrderElementsOf(List.of(-1, 1));
}

@Test
void threeSum() {
int[] nums = new int[]{-1, 0, 1, 2, -1, -4};
Arrays.sort(nums);
System.out.println("nums = " + Arrays.toString(nums));
int i = 0, j, k;
int ni = 0, nj, nk;
Set<List<Integer>> res = new HashSet<>();
while (i < nums.length && ni <= 0) {
ni = nums[i];
j = i + 1;
k = nums.length - 1;
while (j < k) {
nj = nums[j];
nk = nums[k];
int sum = ni + nj + nk;
if (sum < 0) {
j++;
} else if (sum > 0) {
k--;
} else {
res.add(List.of(ni, nj, nk));
j++;
}
}
i++;
}
assertThat(res).containsExactlyInAnyOrderElementsOf(
List.of(List.of(-1, -1, 2),
List.of(-1, 0, 1)));
}
}

0 comments on commit c2363e7

Please sign in to comment.