Share the joy
leetcode 18.
Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.
Note: The solution set must not contain duplicate quadruplets.
For example, given array S = [1, 0, -1, 0, -2, 2], and target = 0. A solution set is: [ [-1, 0, 0, 1], [-2, -1, 1, 2], [-2, 0, 0, 2] ]
Solution. 3 Sum outer loop uses i, inner loop uses lo, hi. For 4 Sum, we need to use outer loop i, j. When i, j are fixed, we loop inner lo, hi.
In order to avoid the duplicate result, every time when we move i, j, lo, hi, we need to move them until to a different element.
public static List<List<Integer>> fourSum(int[] nums, int target) { List<List<Integer>> ans = new ArrayList<>(); Arrays.sort(nums); int i = 0; while (i < nums.length - 3) { int j = i + 1; while (j < nums.length - 2) { int lo = j + 1, hi = nums.length - 1; while (lo < hi) { int sum = nums[i] + nums[j] + nums[lo] + nums[hi]; if (sum == target) { ans.add(Arrays.asList(nums[i], nums[j], nums[lo], nums[hi])); while (++lo < hi && nums[lo] == nums[lo - 1]); // one line technique to move lo until a different element. while (lo < --hi && nums[hi] == nums[hi + 1]); } else if (sum > target) { hi--; } else { lo++; } } while (++j < nums.length - 2 && nums[j] == nums[j - 1]); } while (++i < nums.length - 3 && nums[i] == nums[i - 1]); } return ans; }
Check my code on github.