3Sum

Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.

Note: The solution set must not contain duplicate triplets.

  1. For example, given array S = [-1, 0, 1, 2, -1, -4],
  2. A solution set is:
  3. [
  4. [-1, 0, 1],
  5. [-1, -1, 2]
  6. ]

Solution:

  1. public class Solution {
  2. public List<List<Integer>> threeSum(int[] num) {
  3. List<List<Integer>> res = new ArrayList<List<Integer>>();
  4. Set<String> set = new HashSet<String>();
  5. Arrays.sort(num);
  6. int n = num.length;
  7. for (int i = 0; i < n - 2; i++) {
  8. int j = i + 1, k = n - 1;
  9. while (j < k) {
  10. int sum = num[i] + num[j] + num[k];
  11. if (sum == 0) {
  12. String key = String.format("%d,%d,%d", num[i], num[j], num[k]);
  13. if (!set.contains(key)) {
  14. set.add(key);
  15. List<Integer> sol = new ArrayList<Integer>();
  16. sol.add(num[i]);
  17. sol.add(num[j]);
  18. sol.add(num[k]);
  19. res.add(sol);
  20. }
  21. j++;
  22. k--;
  23. } else if (sum < 0) {
  24. j++;
  25. } else {
  26. k--;
  27. }
  28. }
  29. }
  30. return res;
  31. }
  32. }

Time complexity: O(n^2)