package com.thealgorithms.misc; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; public class ThreeSumProblem { public List> bruteForce(int[] nums, int target) { List> arr = new ArrayList>(); for (int i = 0; i < nums.length; i++) { for (int j = i + 1; j < nums.length; j++) { for (int k = j + 1; k < nums.length; k++) { if (nums[i] + nums[j] + nums[k] == target) { List temp = new ArrayList<>(); temp.add(nums[i]); temp.add(nums[j]); temp.add(nums[k]); Collections.sort(temp); arr.add(temp); } } } } arr = new ArrayList>(new LinkedHashSet>(arr)); return arr; } public List> twoPointer(int[] nums, int target) { Arrays.sort(nums); List> arr = new ArrayList>(); int start = 0; int end = 0; int i = 0; while (i < nums.length - 1) { start = i + 1; end = nums.length - 1; while (start < end) { if (nums[start] + nums[end] + nums[i] == target) { List temp = new ArrayList<>(); temp.add(nums[i]); temp.add(nums[start]); temp.add(nums[end]); arr.add(temp); start++; end--; } else if (nums[start] + nums[end] + nums[i] < target) { start += 1; } else { end -= 1; } } i++; } Set> set = new LinkedHashSet>(arr); return new ArrayList>(set); } public List> hashMap(int[] nums, int target) { Arrays.sort(nums); Set> ts = new HashSet<>(); HashMap hm = new HashMap<>(); for (int i = 0; i < nums.length; i++) { hm.put(nums[i], i); } for (int i = 0; i < nums.length; i++) { for (int j = i + 1; j < nums.length; j++) { int t = target - nums[i] - nums[j]; if (hm.containsKey(t) && hm.get(t) > j) { List temp = new ArrayList<>(); temp.add(nums[i]); temp.add(nums[j]); temp.add(t); ts.add(temp); } } } return new ArrayList<>(ts); } }