这个题很简单,还是取一个值,然后另外两个值从两端向中间逼近

public class Solution {
    public int threeSumClosest(int[] nums, int target) {
        int length = nums.length;
        List<Integer> numList = new ArrayList<Integer>(length);
        for (int num : nums) {
            numList.add(num);
        }
        Collections.sort(numList);
        int sum1 = numList.get(0) + numList.get(1) + numList.get(2);
        int sum2 = numList.get(length-1) + numList.get(length-2) + numList.get(length-3);
        int max1 = distance(sum1, target);
        int max2 = distance(sum2, target);
        int max = max1 < max2? max1:max2;
        int targetSum = max1 < max2? sum1: sum2;
        for (int i = 0; i < length - 2; i++) {
            int p = i+1;
            int q = length - 1;
            while (p < q) {
                int sum = numList.get(i) + numList.get(p) + numList.get(q);
                int dis = distance(sum, target);
                if (dis == 0) {
                    return target;
                }
                if (dis < max) {
                    targetSum = sum;
                    max = dis;
                }
                if (sum < target) {
                    p++;
                } else {
                    q--;
                }
            }
        }
        return targetSum;
    }
    
    private int distance(int source, int target) {
        if (source > target) {
            return source - target;
        } else {
            return target - source;
        }
    }
}

chenatu
106 声望12 粉丝