class Solution {
public List<List<Integer>> fourSum(int[] nums, int target) {
List<List<Integer>> res = new ArrayList<List<Integer>>();
if(nums == null || nums.length <= 3) return res;
Arrays.sort(nums);
int index = 0;
while(index < nums.length - 3 ){//外层嵌套一个循环
int i = index + 1;//第二个数的起始位置为第一个数的后一位,后面就相当于threeSum
while(i < nums.length-2){
int base = nums[i];
int left = i+1;
int right = nums.length-1;
while(left < right){
int sum = nums[index] + base + nums[right] + nums[left];
if(sum == target){
LinkedList<Integer> list = new LinkedList<Integer>();
list.add(nums[index]);
list.add(base);
list.add(nums[left]);
list.add(nums[right]);
res.add(list);
left = moveRight(nums,left+1);
right = moveLeft(nums,right-1);
}
else if(sum > target){
right = moveLeft(nums,right-1);
}
else{
left = moveRight(nums,left+1);
}
}
i = moveRight(nums, i+1);
}
index = moveRight(nums, index+1);
}
return res;
}
public int moveLeft(int[] nums, int right){
while((nums[right] == nums[right+1] && right > 0) || right == nums.length-1){
right--;
}
return right;
}
public int moveRight(int[] nums, int left){
while((nums[left] == nums[left-1] && left < nums.length-1) || left == 0){
left++;
}
return left;
}
}
归纳:
注意四个指针的初始位置和移动方向,第一个、第二个和第三个指针的初始位置是挨着的