# 四数之和(leetcode18)

[
[-1, 0, 0, 1],
[-2, -1, 1, 2],
[-2, 0, 0, 2]
]

• 每一种循环枚举到的下标必须大于上一重循环枚举到的下标；
• 同一重循环中，如果当前元素与上一个元素相同，则跳过当前元素；

public class leetcode18 {

public static void main(String[] args) {
// TODO Auto-generated method stub

Scanner in = new Scanner(System.in);
String[] numsStr = in.nextLine().split(",");
int[] nums = new int[numsStr.length];
for(int i=0;i<numsStr.length;i++){
nums[i] = Integer.parseInt(numsStr[i]);
}

int target = Integer.parseInt(in.nextLine());
List<List<Integer>> result = fourSum(nums,target);
System.out.println(result);
}

public static List<List<Integer>> fourSum(int[] nums, int target) {
if(nums==null||nums.length<4){
}
Arrays.sort(nums);
int length = nums.length;
for(int i=0;i<length-3;i++){
if(i>0&&nums[i]==nums[i-1]){
continue;
}
if(nums[i]+nums[i+1]+nums[i+2]+nums[i+3]>target){
break;
}
if(nums[i]+nums[length-3]+nums[length-2]+nums[length-1]<target){
continue;
}
for(int j=i+1;j<length-2;j++){
if(j>i+1&&nums[j]==nums[j-1]){
continue;
}
if(nums[i]+nums[j]+nums[j+1]+nums[j+2]>target){
break;
}
if(nums[i]+nums[j]+nums[length-2]+nums[length-1]<target){
continue;
}
int left=j+1,right=length-1;
while(left<right){
int sum = nums[i]+nums[j]+nums[left]+nums[right];
if(sum==target){
while(left<right&&nums[left]==nums[left+1]){
left++;
}
left++;
while(left<right&&nums[right]==nums[right-1]){
right--;
}
right--;
}else if(sum<target){
left++;
}else{
right--;
}
}
}
}