Title Description:
Given an array S of n integers, is 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.
Problem Solving Analysis:
This and 3Sum the problem somewhat like, also must first determine two number, then two number of determination can refer to binary search implementation method to optimize.
Specific code:
1 Public classSolution {2 Public StaticList<list<integer>> Foursum (int[] Nums,inttarget) {3 Arrays.sort (nums);4 //the judgment of the boundary condition5list<list<integer>> results =NewArraylist<list<integer>>();6 if(nums.length<4){7 returnresults;8 }9 if(nums.length==4){Ten if(nums[0]+nums[1]+nums[2]+nums[3]==target) { Onelist<integer> result =NewArraylist<integer>(); AResult.add (nums[0]); -Result.add (nums[1]); -Result.add (nums[2]); theResult.add (nums[3]); - Results.add (result); - - } + returnresults; - } + //to determine the position of the first two numbers by ergodic method A for(intfirst=0;first<nums.length-3;first++){ at for(intsecond=first+1;second<nums.length-2;second++){ - //the third and fourth numbers are determined with a binary lookup - intThird=second+1; - intFourth=nums.length-1; - while(third<Fourth) { - if(nums[first]+nums[second]+nums[third]+nums[fourth]>target) { infourth--; - } to Else if(nums[first]+nums[second]+nums[third]+nums[fourth]<target) { +third++; - } the Else{ *list<integer> result =NewArraylist<integer>(); $ Result.add (Nums[first]);Panax Notoginseng Result.add (Nums[second]); - Result.add (Nums[third]); the Result.add (Nums[fourth]); + Results.add (result); A //Avoid element duplication the while(third<nums.length-1&&nums[third+1]==Nums[third]) { +third++; - } $third++; $ //Avoid element duplication - while(third<fourth&&nums[fourth-1]==Nums[fourth]) { -fourth--; the } -fourth--;Wuyi the } - } Wu //Avoid element duplication - while(second<nums.length-2&&nums[second+1]==Nums[second]) { Aboutsecond++; $ } - } - //Avoid element duplication - while(first<nums.length-3&&nums[first+1]==Nums[first]) { Afirst++; + } the } - returnresults; $ } the}
"Leetcode" 18. 4Sum