LeetCode 3Sum Closest

16. 3Sum Closest

Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution.

For example, given array S = {-1 2 1 -4}, and target = 1.

The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).

方法

第一眼看到这道题目直观的方法就是用DFS,result的初始值设置为nums[0]+nums[1]+nums[2],并不会因为数组中存在负数,所以result的初始值没法取。以下测试用例正确:[1,1,-1,-1,3] -1

public class Solution {
    public int result = Integer.MAX_VALUE;
    public int threeSumClosest(int[] nums, int target) {
        if(nums.length == 0){
            return 0;
        }
        judge(nums, 0, new ArrayList<Integer>(), target);
        return result;
    }
    public void judge(int[] nums, int pos, ArrayList<Integer> array, int target){
        if(array.size() == 3){
            int res = 0;
            for(int i = 0; i < 3; i++){
                res = res + array.get(i);
            }
            if(Math.abs(result-target) > Math.abs(res-target)){
                result = res;
            }
            return;
        }
        for(int i = pos; i < nums.length; i++){
            array.add(nums[i]);
            judge(nums,i+1,array,target);
            array.remove(array.size()-1);
        }
        return;
    }
}

正确方法:

排序,使用三个指针。 i = 循环变量, j = 循环变量+1, k = 数组最后位数。若 >target,则k–,否则j++,跳出条件j<k

public class Solution {
    public int threeSumClosest(int[] nums, int target) {
        if(nums.length == 0 || nums.length < 3){
            return 0;
        }
        int result = nums[0]+nums[1]+nums[2];
        Arrays.sort(nums);
        for(int i = 0; i < nums.length; i++){
            int start = i + 1;
            int end = nums.length-1;
            while(start < end){
                int res = nums[i] + nums[start] + nums[end];
                if(res > target){
                    end--;
                }else{
                    start++; //无论res==target或者res<target,start都自增
                }
                if(Math.abs(result-target) > Math.abs(res-target)){
                    result = res;
                }
            }
        }

        return result;
    }
}
Share