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
Elements in a quadruplet (a,b,c,d) must be in non-descending order. (ie, a ≤ b ≤ c ≤ d)
The solution set must not contain duplicate quadruplets.
Example
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)
解题思路:看到提示是使用Hashmap来做,没想到怎么处理。自己实现了全部迭代的解法,全部迭代因为不会出现重复计算,所以计算量也还是可以控制。参考网上的解法,实现双指针夹逼解法。
解法一:
public class Solution { /** * @param numbers : Give an array numbersbers of n integer * @param target : you need to find four elements that's sum of target * @return : Find all unique quadruplets in the array which gives the sum of * zero. */ public ArrayList<ArrayList<Integer>> fourSum(int[] numbers, int target) { Arrays.sort(numbers); ArrayList<ArrayList<Integer>> res = find(numbers, target, 0, 4); return res == null ? new ArrayList<ArrayList<Integer>>() : res; } public ArrayList<ArrayList<Integer>> find(int[] numbers, int target, int i, int n) { int N = numbers.length; if (n == 1) { while (i < N && numbers[i] != target) i++; if (i < N) { ArrayList<Integer> l = new ArrayList<Integer>(); l.add(numbers[i]); ArrayList<ArrayList<Integer>> list = new ArrayList<ArrayList<Integer>>(); list.add(l); return list; } else return null; } else { int t = i; ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>(); while (t + n <= N) { if (t > i && numbers[t] == numbers[t - 1]) { t++; continue; } target = target - numbers[t]; ArrayList<ArrayList<Integer>> list = find(numbers, target, t + 1, n - 1); if (list != null) { for (ArrayList l : list) { l.add(0, numbers[t]); res.add(l); } } target = target + numbers[t]; t++; } if (res.size() > 0) return res; else return null; } } }
解法二:
public class Solution { /** * @param numbers : Give an array numbersbers of n integer * @param target : you need to find four elements that's sum of target * @return : Find all unique quadruplets in the array which gives the sum of * zero. */ public ArrayList<ArrayList<Integer>> fourSum(int[] numbers, int target) { Arrays.sort(numbers); ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>(); if (numbers == null || numbers.length < 4) return res; int N = numbers.length; for (int i = 0; i < N - 3; i++) { for (int j = i + 1; j < N - 2; j++) { int l = j + 1; int h = N - 1; while (l < h) { int sum = numbers[i] + numbers[j] + numbers[l] + numbers[h]; if (sum < target) l++; else if (sum > target) h--; else { boolean find = false; for (ArrayList<Integer> ll : res) { if (ll.get(0) == numbers[i] && ll.get(1) == numbers[j] && ll.get(2) == numbers[l] && ll.get(3) == numbers[h]) find = true; } if (!find) { ArrayList<Integer> ll = new ArrayList<Integer>(); ll.add(numbers[i]); ll.add(numbers[j]); ll.add(numbers[l]); ll.add(numbers[h]); res.add(ll); } l++; h--; } } } } return res; } }
时间: 2024-10-11 09:51:09