18.四数之和
class Solution {
public List<List<Integer>> fourSum(int[] nums, int target) {
int length=nums.length;
Arrays.sort(nums);
List<List<Integer>> ans=new ArrayList<List<Integer>>();
if(nums==null&&nums.length<4){
return ans;
}
for(int first=0;first<length-3;first++){
if(first>0&&nums[first]==nums[first-1]){
continue;
}
if(nums[first]+nums[first+1]+nums[first+2]+nums[first+3]>target){
break;
}
if(nums[first]+nums[length-3]+nums[length-2]+nums[length-1]<target){
continue;
}
for(int second=first+1;second<length-2;second++){
if(second>first+1&&nums[second]==nums[second-1]){
continue;
}
if(nums[first]+nums[second]+nums[second+1]+nums[second+2]>target){
break;
}
if(nums[first]+nums[second]+nums[length-2]+nums[length-1]<target){
continue;
}
int third=second+1;
int forth=length-1;
while(third<forth){
int sum=nums[first]+nums[second]+nums[third]+nums[forth];
if(sum==target){
ans.add(Arrays.asList(nums[first],nums[second],nums[third],nums[forth]));
while(third<forth&&nums[third+1]==nums[third]){
third++;
}
third++;
while(third<forth&&nums[forth-1]==nums[forth]){
forth--;
}
forth--;
}else if(sum<target){
third ++;
}else{
forth--;
}
}
}
}
return ans;
}
}