//day08:三数之和。思路:先排序,然后遍历每一个数字的同时,再设置两个指针left/right
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> res = new ArrayList<>();
Arrays.sort(nums);
for(int i=0;i<nums.length-2;i++){
if(i >=1 && nums[i] == nums[i-1])
continue;
int left = i+1;
int right = nums.length -1;
while(left < right){
int sum = nums[i] + nums[left] + nums[right];
if(sum == 0){
List<Integer> tmp = new ArrayList<>();
tmp.add(nums[i]);
tmp.add(nums[left]);
tmp.add(nums[right]);
res.add(tmp);
while(left+1 < right && nums[left] == nums[left+1])
left++;
while(right-1>left && nums[right] == nums[right-1])
right--;
left++;
right--;
}
else if(sum > 0)
right--;
else
left++;
}
}
return res;
}
/**
day08:最接近的三数之和(时间效率太低)
思路:dfs
*/
public int threeSumClosest(int[] nums, int target) {
int[] res = {Integer.MAX_VALUE};
helper(res, nums, target, 0, 0, 0);
return res[0];
}
public static void helper(int[] res, int[] nums,int target, int pos, int sum, int count){
if(count == 3){
//特殊情况
if(res[0] == Integer.MAX_VALUE && target <= 0){
res[0] = sum;
return;
}
if(Math.abs(sum - target) < Math.abs(res[0] - target))
res[0] = sum;
return;
}
for(int i=pos;i<nums.length;i++){
helper(res, nums,target, i+1, sum+nums[i], count+1);
}
}