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.輸入一個長度爲n的整數數組和一個目標整數target,咱們須要找出是否存在4個元素a、b、c、d,使得abcd的和等於target。若是有,輸出這樣的非重複的元素序列。數組
For example, 輸入數組S = [1, 0, -1, 0, -2, 2], 目標整數target = 0.
返回的結果集是:
[
[-1, 0, 0, 1],
[-2, -1, 1, 2],
[-2, 0, 0, 2]
]指針
public List<List<Integer>> fourSum(int[] nums, int target) { Arrays.sort(nums); List<List<Integer>> res = new ArrayList<List<Integer>>(); int length = nums.length; if(length<4 || target > nums[length-1]*4 || target < nums[0]*4)return res; for(int i=0;i<length-3;i++){ if(i == 0 || (i>0 && nums[i] != nums[i-1])){ for(int j=i+1;j<length-2;j++){ if((j == i+1 || nums[j] != nums[j-1])){ int tempTarget = target-nums[i]-nums[j]; int low = j+1; int high = length-1; while(low < high){ if(nums[low]+nums[high] == tempTarget){ res.add(Arrays.asList(nums[i],nums[j],nums[low],nums[high])); while(low < high && nums[low] == nums[low+1])low++; while(low < high && nums[high] == nums[high-1])high--; low++; high--; }else if(nums[low] + nums[high] > tempTarget){ high--; }else{ low++; } } } } } } return res; }