一、题目叙述:
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] ]
Subscribe to see which companies asked this question
二、解题思路:
搞不懂,我用了和15题一模一样的算法,就把15题3Sum的算法加了个循环和防止重复的判断,就过了。。。。。。
(1)主体思路:循环前三个数,然后二分查找(所以数组要先排序)为target减去前三数和的第四个数,这样复杂度能从O(n4)减到O(n3logn)。
完全照搬15题。。。
三、源码:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Solution
{
List<List<Integer>> ans = new ArrayList<List<Integer>>();
public List<List<Integer>> fourSum(int[] nums, int target)
{
Arrays.sort(nums);
int q;
int h;
//int count = 0;
//List<List<Integer>> reslist = new ArrayList<List<Integer>>();
for (int i = 0; i < nums.length; i ++)
{
if (i > 0 && nums[i] == nums[i-1]) continue;//去除重复
for (int j = i + 1; j < nums.length; j++)
{
if (j > i+1 && nums[j] == nums[j-1]) continue;//去除重复
for (int k = j + 1; k < nums.length; k++)
{
if (k > j+1 && nums[k] == nums[k-1]) continue;
q = BinarySearch(target-nums[i]-nums[j]-nums[k], nums, k+1, nums.length - 1);
if (q > k)
{
//count ++;
List<Integer> list = new ArrayList<Integer>();
list.add(nums[i]);
list.add(nums[j]);
list.add(nums[k]);
list.add(nums[q]);
ans.add(list);
}
}
}
}
return ans;
}
public int BinarySearch (int k,int[] num,int first, int last)
{
//int first = 0;
//int last = num.length - 1;
int mid;
while (first <= last)
{
mid = (first + last) / 2;
if (num[mid] > k) last =mid - 1;
else if (num[mid] < k) first = mid + 1;
else return mid;
}
return -1;
}
public static void main(String args[])
{
int[] a = {1, 0, -1, 0, -2, 2};
Solution so = new Solution();
System.out.println(so.fourSum(a, 0));
}
}