Advertisement
Guest User

Untitled

a guest
Oct 15th, 2019
144
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.85 KB | None | 0 0
  1. class 3SumProblem {
  2. Map<Integer, HashSet<Integer>> entryIndexMap = new HashMap<>();
  3. public List<List<Integer>> threeSum(int[] nums) {
  4. Arrays.sort(nums);
  5. List<List<Integer>> sumList = new ArrayList<>();
  6.  
  7. for (int i = 0; i < nums.length; i++) {
  8. int num = nums[i];
  9. HashSet<Integer> indices = entryIndexMap.get(num);
  10. if (indices != null) {
  11. indices.add(i);
  12. } else {
  13. indices = new HashSet<>();
  14. indices.add(i);
  15. entryIndexMap.put(num, indices);
  16. }
  17. }
  18.  
  19. for (int i = 0; i < nums.length - 1; i++) {
  20. // We are skipping the parts where there is repeated continuous values of i and j. Because these are going to lead to repeated solution
  21. if (!(i > 0 && nums[i] == nums[i - 1])) {
  22. for (int j = i + 1; j < nums.length; j++) {
  23. if (!(j > i + 1 && nums[j] == nums[j - 1])) {
  24. int sum = nums[i] + nums[j];
  25. int remaining = 0 - sum;
  26. if (entryIndexMap.get(remaining) != null) {
  27. Set<Integer> indices = entryIndexMap.get(remaining);
  28. for (int index : indices) {
  29. if (index > i && index > j) {
  30. List<Integer> list = new ArrayList<>();
  31. list.add(nums[i]);
  32. list.add(nums[j]);
  33. list.add(nums[index]);
  34. sumList.add(list);
  35. break;
  36. }
  37. }
  38. }
  39. }
  40. }
  41. }
  42. }
  43. return sumList;
  44. }
  45. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement