Skip to content

Instantly share code, notes, and snippets.

@thmain
Last active July 6, 2024 01:40
Show Gist options
  • Save thmain/538fae574c6070dcc270ab0456348a4c to your computer and use it in GitHub Desktop.
Save thmain/538fae574c6070dcc270ab0456348a4c to your computer and use it in GitHub Desktop.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class ThreeSum {
public static List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> result = new ArrayList<>();
Arrays.sort(nums);
for (int i = 0; i < nums.length - 2; i++) {
if (i > 0 && nums[i] == nums[i - 1]) {
continue; // Skip duplicate elements
}
int j = i + 1;
int k = nums.length - 1;
while (j < k) {
int sum = nums[i] + nums[j] + nums[k];
if (sum == 0) {
result.add(Arrays.asList(nums[i], nums[j], nums[k]));
// Skip duplicates for j and k
while (j < k && nums[j] == nums[j + 1]) {
j++;
}
while (j < k && nums[k] == nums[k - 1]) {
k--;
}
j++;
k--;
} else if (sum > 0) {
k--;
} else {
j++;
}
}
}
return result;
}
public static void main(String[] args) {
System.out.println(threeSum(new int[]{-1, 0, 1, 2, -1, -4}));
System.out.println(threeSum(new int[]{0, 1, 1}));
System.out.println(threeSum(new int[]{0, 0, 0}));
System.out.println(threeSum(new int[]{-2, 0, 1, 1, 2}));
System.out.println(threeSum(new int[]{1, 2, -2, -1}));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment